iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Springboot怎么整合minio实现文件服务
  • 622
分享到

Springboot怎么整合minio实现文件服务

2023-06-30 18:06:32 622人浏览 薄情痞子
摘要

本篇内容介绍了“SpringBoot怎么整合miNIO实现文件服务”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!首先pom文件引入相关依赖&

本篇内容介绍了“SpringBoot怎么整合miNIO实现文件服务”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

首先pom文件引入相关依赖

        <!--minio-->        <dependency>            <groupId>io.minio</groupId>            <artifactId>minio</artifactId>            <version>3.0.10</version>        </dependency>

springboot配置文件application.yml 里配置minio信息

#minio配置minio:  endpoint: Http://${minio_host:172.16.10.21}:9000/  accessKey: ${minio_user:minioadmin}  secreTKEy: ${minio_pwd:minioadmin}  bucket: ${minio_space:spacedata}  http-url: http://${minio_url:172.16.10.21}:9000/  imgSize: 10485760  fileSize: 1048576000

创建MinioItem字段项目

import io.minio.messages.Item;import io.minio.messages.Owner;import io.swagger.annotations.apiModelProperty;import lombok.Data; import java.util.Date; @Datapublic class MinioItem {        @ApiModelProperty("对象名称")    private String objectName;        @ApiModelProperty("最后操作时间")    private Date lastModified;    private String etag;        @ApiModelProperty("对象大小")    private String size;    private String storageClass;    private Owner owner;        @ApiModelProperty("对象类型:directory(目录)或file(文件)")    private String type;     public MinioItem(String objectName, Date lastModified, String etag, String size, String storageClass, Owner owner, String type) {        this.objectName = objectName;        this.lastModified = lastModified;        this.etag = etag;        this.size = size;        this.storageClass = storageClass;        this.owner = owner;        this.type = type;    }      public MinioItem(Item item) {        this.objectName = item.objectName();        this.type = item.isDir() ? "directory" : "file";        this.etag = item.etag();        long sizeNum = item.objectSize();        this.size = sizeNum > 0 ? convertFileSize(sizeNum):"0";        this.storageClass = item.storageClass();        this.owner = item.owner();        try {            this.lastModified = item.lastModified();        }catch(NullPointerException e){}    }     public String convertFileSize(long size) {        long kb = 1024;        long mb = kb * 1024;        long gb = mb * 1024;        if (size >= gb) {            return String.fORMat("%.1f GB", (float) size / gb);        } else if (size >= mb) {            float f = (float) size / mb;            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);        } else if (size >= kb) {            float f = (float) size / kb;            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);        } else{            return String.format("%d B", size);        }    }}

创建MinioTemplate模板类

import com.GIS.spacedata.domain.dto.minio.MinioItem;import com.Google.common.collect.Lists;import io.minio.Minioclient;import io.minio.ObjectStat;import io.minio.Result;import io.minio.errors.*;import io.minio.messages.Bucket;import io.minio.messages.Item;import lombok.RequiredArgsConstructor;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.InitializingBean;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.HttpHeaders;import org.springframework.http.httpstatus;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Component;import org.springframework.util.FileCopyUtils;import org.xmlpull.v1.XmlPullParserException; import javax.servlet.http.HttpServletRequest;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.URL;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.util.ArrayList;import java.util.List;import java.util.Optional; @Slf4j@Component@RequiredArgsConstructorpublic class MinioTemplate implements InitializingBean {         @Value("${minio.endpoint}")    private String endpoint;         @Value("${minio.accessKey}")    private String accessKey;         @Value("${minio.secretKey}")    private String secretKey;         @Value("${minio.http-url}")    private String httpUrl;     @Value("${minio.bucket}")    private String bucket;     private static MinioClient minioClient;     @Override    public void afterPropertiesSet() throws Exception {        minioClient = new MinioClient(endpoint, accessKey, secretKey);    }     @SneakyThrows    public boolean bucketExists(String bucketName) {        return minioClient.bucketExists(bucketName);    }         @SneakyThrows    public void createBucket(String bucketName) {        if (!bucketExists(bucketName)) {            minioClient.makeBucket(bucketName);        }    }         @SneakyThrows    public List<Bucket> getAllBuckets() {        return minioClient.listBuckets();    }         @SneakyThrows    public Optional<Bucket> getBucket(String bucketName) {        return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();    }         @SneakyThrows    public void removeBucket(String bucketName) {        minioClient.removeBucket(bucketName);    }         @SneakyThrows    public List<MinioItem> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {        List<MinioItem> objectList = new ArrayList<>();        Iterable<Result<Item>> objectsIterator = minioClient.listObjects(bucketName, prefix, recursive);        for (Result<Item> result : objectsIterator) {            objectList.add(new MinioItem(result.get()));        }        return objectList;    }         @SneakyThrows    public String getObjectURL(String bucketName, String objectName, Integer expires) {        return minioClient.presignedGetObject(bucketName, objectName, expires);    }         @SneakyThrows    public String getObjectURL(String bucketName, String objectName) {        return minioClient.presignedGetObject(bucketName, objectName);    }         @SneakyThrows    public String getObjectUrl(String bucketName, String objectName) {        return minioClient.getObjectUrl(bucketName, objectName);    }         @SneakyThrows    public InputStream getObject(String bucketName, String objectName) {        return minioClient.getObject(bucketName, objectName);    }         public void putObject(String bucketName, String objectName, InputStream stream) throws Exception {        String contentType = "application/octet-stream";        if ("JSON".equals(objectName.split("\\.")[1])) {            //json格式,c++编译生成文件,需要直接读取            contentType = "application/json";        }        minioClient.putObject(bucketName, objectName, stream, stream.available(), contentType);    }         public void putObject(String bucketName, String objectName, InputStream stream, long size, String contextType) throws Exception {        minioClient.putObject(bucketName, objectName, stream, size, contextType);    }         public ObjectStat getObjectInfo(String bucketName, String objectName) throws Exception {        return minioClient.statObject(bucketName, objectName);    }         public void removeObject(String bucketName, String objectName) {        try {            if (StringUtils.isNotBlank(objectName)) {                if (objectName.endsWith(".") || objectName.endsWith("/")) {                    Iterable<Result<Item>> list = minioClient.listObjects(bucketName, objectName);                    list.forEach(e -> {                        try {                            minioClient.removeObject(bucketName, e.get().objectName());                        } catch (InvalidBucketNameException invalidBucketNameException) {                            invalidBucketNameException.printStackTrace();                        } catch (NoSuchAlgorithmException noSuchAlgorithmException) {                            noSuchAlgorithmException.printStackTrace();                        } catch (InsufficientDataException insufficientDataException) {                            insufficientDataException.printStackTrace();                        } catch (IOException ioException) {                            ioException.printStackTrace();                        } catch (InvalidKeyException invalidKeyException) {                            invalidKeyException.printStackTrace();                        } catch (NoResponseException noResponseException) {                            noResponseException.printStackTrace();                        } catch (XmlPullParserException xmlPullParserException) {                            xmlPullParserException.printStackTrace();                        } catch (ErrorResponseException errorResponseException) {                            errorResponseException.printStackTrace();                        } catch (InternalException internalException) {                            internalException.printStackTrace();                        }                    });                }            }        } catch (XmlPullParserException e) {            e.printStackTrace();        }    }         public void downloadTargetDir(String bucketName, String objectName, String dirPath) {        try {            if (StringUtils.isNotBlank(objectName)) {                if (objectName.endsWith(".") || objectName.endsWith("/")) {                    Iterable<Result<Item>> list = minioClient.listObjects(bucketName, objectName);                    list.forEach(e -> {                        try {                            String url = minioClient.getObjectUrl(bucketName, e.get().objectName());                            getFile(url, dirPath);                        } catch (InvalidBucketNameException invalidBucketNameException) {                            invalidBucketNameException.printStackTrace();                        } catch (NoSuchAlgorithmException noSuchAlgorithmException) {                            noSuchAlgorithmException.printStackTrace();                        } catch (InsufficientDataException insufficientDataException) {                            insufficientDataException.printStackTrace();                        } catch (IOException ioException) {                            ioException.printStackTrace();                        } catch (InvalidKeyException invalidKeyException) {                            invalidKeyException.printStackTrace();                        } catch (NoResponseException noResponseException) {                            noResponseException.printStackTrace();                        } catch (XmlPullParserException xmlPullParserException) {                            xmlPullParserException.printStackTrace();                        } catch (ErrorResponseException errorResponseException) {                            errorResponseException.printStackTrace();                        } catch (InternalException internalException) {                            internalException.printStackTrace();                        }                    });                }            }        } catch (XmlPullParserException e) {            e.printStackTrace();        }    }      public static void main(String[] args) throws            NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException {        try {            // 使用MinIO服务的URL,端口,Access key和Secret key创建一个MinioClient对象            MinioClient minioClient = new MinioClient("http://172.16.10.201:9000/", "minioadmin", "minioadmin");             // 检查存储桶是否已经存在            boolean isExist = minioClient.bucketExists("spacedata");            if (isExist) {                System.out.println("Bucket already exists.");            } else {                // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。                minioClient.makeBucket("spacedata");            }             // 使用putObject上传一个文件到存储桶中。            //  minioClient.putObject("spacedata", "测试.jpg", "C:\\Users\\sundasheng44\\Desktop\\1.png");             //  minioClient.removeObject("spacedata", "20200916/8ca27855ba884d7da1496fb96907a759.dwg");            Iterable<Result<Item>> list = minioClient.listObjects("spacedata", "CompileResult/");            List<String> list1 = Lists.newArrayList();            list.forEach(e -> {                try {                    list1.add("1");                    String url = minioClient.getObjectUrl("spacedata", e.get().objectName());                    System.out.println(url);                    //getFile(url, "C:\\Users\\liuya\\Desktop\\" + e.get().objectName());                    System.out.println(e.get().objectName());                    //   minioClient.removeObject("spacedata", e.get().objectName());                } catch (InvalidBucketNameException invalidBucketNameException) {                    invalidBucketNameException.printStackTrace();                } catch (NoSuchAlgorithmException noSuchAlgorithmException) {                    noSuchAlgorithmException.printStackTrace();                } catch (InsufficientDataException insufficientDataException) {                    insufficientDataException.printStackTrace();                } catch (IOException ioException) {                    ioException.printStackTrace();                } catch (InvalidKeyException invalidKeyException) {                    invalidKeyException.printStackTrace();                } catch (NoResponseException noResponseException) {                    noResponseException.printStackTrace();                } catch (XmlPullParserException xmlPullParserException) {                    xmlPullParserException.printStackTrace();                } catch (ErrorResponseException errorResponseException) {                    errorResponseException.printStackTrace();                } catch (InternalException internalException) {                    internalException.printStackTrace();                }            });            System.out.println(list1.size());        } catch (MinioException e) {            System.out.println("Error occurred: " + e);        }    }         public ResponseEntity<byte[]> fileDownload(String url, String fileName, HttpServletRequest request) {        return this.downloadMethod(url, fileName, request);    }     private File getFile(String url, String fileName) {        InputStream in = null;        // 创建文件        String dirPath = fileName.substring(0, fileName.lastIndexOf("/"));        File dir = new File(dirPath);        if (!dir.exists()) {            dir.mkdirs();        }        File file = new File(fileName);        try {            URL url1 = new URL(url);            in = url1.openStream();            // 输入流转换为字节流            byte[] buffer = FileCopyUtils.copyToByteArray(in);            // 字节流写入文件            FileCopyUtils.copy(buffer, file);            // 关闭输入流            in.close();        } catch (IOException e) {            log.error("文件获取失败:" + e);            return null;        } finally {            try {                in.close();            } catch (IOException e) {                log.error("", e);            }        }        return file;    }     public ResponseEntity<byte[]> downloadMethod(String url, String fileName, HttpServletRequest request) {        HttpHeaders heads = new HttpHeaders();        heads.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream; charset=utf-8");        try {            if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {                // firefox浏览器                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {                // IE浏览器                fileName = URLEncoder.encode(fileName, "UTF-8");            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("EDGE") > 0) {                // WIN10浏览器                fileName = URLEncoder.encode(fileName, "UTF-8");            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {                // 谷歌                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");            } else {                //万能乱码问题解决                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);            }        } catch (UnsupportedEncodingException e) {            // log.error("", e);        }        heads.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);        try {            //InputStream in = new FileInputStream(file);            URL url1 = new URL(url);            InputStream in = url1.openStream();            // 输入流转换为字节流            byte[] buffer = FileCopyUtils.copyToByteArray(in);            ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(buffer, heads, HttpStatus.OK);            //file.delete();            return responseEntity;        } catch (Exception e) {            log.error("", e);        }        return null;    }

创建 FilesMiniOService 服务类

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.gis.spacedata.common.constant.response.ResponseCodeConst;import com.gis.spacedata.common.domain.ResponseDTO;import com.gis.spacedata.domain.dto.file.vo.UploadVO;import com.gis.spacedata.domain.dto.minio.MinioItem;import com.gis.spacedata.domain.entity.file.FileEntity;import com.gis.spacedata.enums.file.FileServiceTypeEnum;import com.gis.spacedata.handler.SmartBusinessException;import com.gis.spacedata.mapper.file.FileDao;import lombok.extern.slf4j.Slf4j;import org.apache.commons.codec.digest.DigestUtils;import org.apache.commons.lang3.StringUtils;import org.springblade.core.tool.utils.FileUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.ResponseEntity;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import org.springframework.stereotype.Service;import org.springframework.WEB.multipart.MultipartFile; import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.List;import java.util.UUID; @Service@Slf4jpublic class FilesMinioService extends ServiceImpl<FileDao, FileEntity> {     @Autowired    private MinioTemplate minioTemplate;     @Resource    private ThreadPoolTaskExecutor taskExecutor;         @Value("#{${minio.imgSize}}")    private Long imgSize;         @Value("#{${minio.fileSize}}")    private Long fileSize;     @Value("${minio.bucket}")    private String bucket;         @Value("${minio.http-url}")    private String httpUrl;         private boolean isImage(String fileName) {        //设置允许上传文件类型        String suffixList = "jpg,gif,png,ico,bmp,jpeg";        // 获取文件后缀        String suffix = fileName.substring(fileName.lastIndexOf(".")                + 1);        return suffixList.contains(suffix.trim().toLowerCase());    }         private void fileCheck(MultipartFile upfile, String fileName) throws Exception {        Long size = upfile.getSize();        if (isImage(fileName)) {            if (size > imgSize) {                throw new Exception("上传对图片大于:" + (imgSize / 1024 / 1024) + "M限制");            }        } else {            if (size > fileSize) {                throw new Exception("上传对文件大于:" + (fileSize / 1024 / 1024) + "M限制");            }        }    }         public ResponseDTO<UploadVO> fileUpload(MultipartFile upfile) throws IOException {        String originalFileName = upfile.getOriginalFilename();        try {            fileCheck(upfile, originalFileName);        } catch (Exception e) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR, e.getMessage());        }        if (StringUtils.isBlank(originalFileName)) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM, "文件名称不能为空");        }        UploadVO vo = new UploadVO();        String url;        //获取文件md5,查找数据库,如果有,则不需要上传了        String md5 = DigestUtils.md5Hex(upfile.getInputStream());        QueryWrapper<FileEntity> query = new QueryWrapper<>();        query.lambda().eq(FileEntity::getMd5, md5);        query.lambda().eq(FileEntity::getStorageType, FileServiceTypeEnum.MINIO_OSS.getLocationType());        FileEntity fileEntity = baseMapper.selectOne(query);        if (null != fileEntity) {            //url = minioTemplate.getObjectURL(bucket,fileEntity.getFileName());            vo.setId(fileEntity.getId());            vo.setFileName(originalFileName);            vo.setUrl(httpUrl + fileEntity.getFileUrl());            vo.setNewFileName(fileEntity.getFileName());            vo.setFileSize(upfile.getSize());            vo.setFileLocationType(FileServiceTypeEnum.MINIO_OSS.getLocationType());            log.info("文件已上传,直接获取");            return ResponseDTO.succData(vo);        }        //拼接文件名        String fileName = generateFileName(originalFileName);        try {            // 检查存储桶是否已经存在            boolean isExist = minioTemplate.bucketExists(bucket);            if (isExist) {                log.info("Bucket already exists.");            } else {                // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。                minioTemplate.createBucket(bucket);            }            // 使用putObject上传一个文件到存储桶中。            minioTemplate.putObject(bucket, fileName, upfile.getInputStream());            log.info("上传成功.");            //生成一个外部链接            //url = minioTemplate.getObjectURL(bucket,fileName);            //已经设置永久链接,直接获取            url = httpUrl + bucket + "/" + fileName;            fileEntity = new FileEntity();            fileEntity.setStorageType(FileServiceTypeEnum.MINIO_OSS.getLocationType());            fileEntity.setFileName(fileName);            fileEntity.setOriginalFileName(originalFileName);            fileEntity.setFileUrl(bucket + "/" + fileName);            fileEntity.setFileSize(upfile.getSize());            fileEntity.setMd5(md5);            baseMapper.insert(fileEntity);        } catch (Exception e) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR, "上传失败!");        }        vo.setFileName(originalFileName);        vo.setId(fileEntity.getId());        vo.setUrl(url);        vo.setNewFileName(fileName);        vo.setFileSize(upfile.getSize());        vo.setFileLocationType(FileServiceTypeEnum.MINIO_OSS.getLocationType());         return ResponseDTO.succData(vo);    }         private String generateFileName(String originalFileName) {        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));        String uuid = UUID.randomUUID().toString().replaceAll("-", "");        String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));        return time + "/" + uuid + fileType;    }         public ResponseDTO<UploadVO> fileUploadRep(MultipartFile upfile) throws IOException {        String originalFileName = upfile.getOriginalFilename();        try {            fileCheck(upfile, originalFileName);        } catch (Exception e) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR, e.getMessage());        }        if (StringUtils.isBlank(originalFileName)) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM, "文件名称不能为空");        }        UploadVO vo = new UploadVO();        String url;        //获取文件md5        FileEntity fileEntity = new FileEntity();        //拼接文件名        String fileName = generateFileName(originalFileName);        try {            // 检查存储桶是否已经存在            boolean isExist = minioTemplate.bucketExists(bucket);            if (isExist) {                log.info("Bucket already exists.");            } else {                // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。                minioTemplate.createBucket(bucket);            }            // 使用putObject上传一个文件到存储桶中。            minioTemplate.putObject(bucket, fileName, upfile.getInputStream());            log.info("上传成功.");            //生成一个外部链接            //url = minioTemplate.getObjectURL(bucket,fileName);            //已经设置永久链接,直接获取            url = httpUrl + bucket + "/" + fileName;            fileEntity.setStorageType(FileServiceTypeEnum.MINIO_OSS.getLocationType());            fileEntity.setFileName(fileName);            fileEntity.setOriginalFileName(originalFileName);            fileEntity.setFileUrl(bucket + "/" + fileName);            fileEntity.setFileSize(upfile.getSize());            baseMapper.insert(fileEntity);        } catch (Exception e) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR, "上传失败!");        }        vo.setFileName(originalFileName);        vo.setId(fileEntity.getId());        vo.setUrl(url);        vo.setNewFileName(fileName);        vo.setFileSize(upfile.getSize());        vo.setFileLocationType(FileServiceTypeEnum.MINIO_OSS.getLocationType());         return ResponseDTO.succData(vo);    }         public ResponseDTO<UploadVO> uploadStream(InputStream inputStream, String originalFileName) {        UploadVO vo = new UploadVO();        String url;        //文件名        String fileName = originalFileName;        try {            // 检查存储桶是否已经存在            boolean isExist = minioTemplate.bucketExists(bucket);            if (isExist) {                log.info("Bucket already exists.");            } else {                // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。                minioTemplate.createBucket(bucket);            }            // 使用putObject上传一个文件到存储桶中。            minioTemplate.putObject(bucket, fileName, inputStream);            log.info("上传成功.");            //生成一个外部链接            //url = minioTemplate.getObjectURL(bucket,fileName);            //已经设置永久链接,直接获取            url = httpUrl + bucket + "/" + fileName;        } catch (Exception e) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR, "上传失败!");        }        vo.setFileName(originalFileName);        vo.setUrl(url);        vo.setNewFileName(fileName);        vo.setFileLocationType(FileServiceTypeEnum.MINIO_OSS.getLocationType());         return ResponseDTO.succData(vo);    }     private String generateFileNameTwo(String originalFileName) {        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));        return time + "/" + originalFileName;    }         public ResponseDTO<UploadVO> findFileById(Long id) {        FileEntity fileEntity = baseMapper.selectById(id);        if (null == fileEntity) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM, "文件不存在");        }        UploadVO vo = new UploadVO();                vo.setFileName(fileEntity.getOriginalFileName());        vo.setUrl(httpUrl + fileEntity.getFileUrl());        vo.setNewFileName(fileEntity.getFileName());        vo.setFileSize(fileEntity.getFileSize());        vo.setFileLocationType(FileServiceTypeEnum.MINIO_OSS.getLocationType());        return ResponseDTO.succData(vo);    }          public ResponseEntity<byte[]> downLoadFile(Long id, HttpServletRequest request) {        FileEntity fileEntity = baseMapper.selectById(id);        if (null == fileEntity) {            throw new SmartBusinessException("文件信息不存在");        }        if (StringUtils.isEmpty(fileEntity.getFileUrl())) {            throw new SmartBusinessException("文件url为空");        }        ResponseEntity<byte[]> stream = minioTemplate.fileDownload(httpUrl + fileEntity.getFileUrl(), fileEntity.getOriginalFileName(), request);        return stream;    }         public ResponseDTO<String> deleteFiles(List<String> fileNames) {        try {            for (String fileName : fileNames) {                minioTemplate.removeObject(bucket, fileName);            }        } catch (Exception e) {            return ResponseDTO.wrap(ResponseCodeConst.ERROR, e.getMessage());        }        return ResponseDTO.succ();    }         public ResponseDTO<String> downloadTargetDir(String objectName, String dirPath) {        minioTemplate.downloadTargetDir(bucket, objectName, dirPath);        return ResponseDTO.succ();    }         public Boolean downloadCompile(String dirPath) {        if (!minioTemplate.bucketExists(bucket)) {            log.info("Bucket not exists.");            return true;        }         List<MinioItem> list = minioTemplate.getAllObjectsByPrefix(bucket, "CompileResult/", true);        list.forEach(e -> {            String url = minioTemplate.getObjectUrl(bucket, e.getObjectName());            InputStream minioStream = minioTemplate.getObject(bucket, e.getObjectName());            File file = new File(dirPath + url.substring(url.indexOf("CompileResult")-1));            if (!file.getParentFile().exists()) {                file.getParentFile().mkdirs();            }            FileUtil.toFile(minioStream, file);        });         log.info("downloadCompile complete.");        return true;    }

部分操作数据库的相关代码省略,不再展示

创建FilesMinioController 服务接口

import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.serializer.SerializerFeature;import com.gis.spacedata.common.anno.NoNeedLogin;import com.gis.spacedata.common.domain.ResponseDTO;import com.gis.spacedata.domain.dto.file.vo.UploadVO;import com.gis.spacedata.service.file.FilesMinioService;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.util.Arrays;import java.util.List; @Api(tags = {"minio文件服务"})@RestControllerpublic class FilesMinioController {     @Autowired    private FilesMinioService filesMinioService;      @ApiOperation(value = "文件上传(md5去重上传) by sunboqiang")    @PostMapping("/minio/uploadFile/md5")    @NoNeedLogin    public ResponseDTO<UploadVO> uploadFile(MultipartFile file) throws IOException {        return filesMinioService.fileUpload(file);    }     @ApiOperation(value = "文件上传(不做重复校验) by sunboqiang")    @PostMapping("/minio/uploadFile/noRepeatCheck")    public ResponseDTO<UploadVO> fileUploadRep(MultipartFile file) throws IOException {        return filesMinioService.fileUploadRep(file);    }     @ApiOperation(value = "文件流上传 by sunboqiang")    @PostMapping("/minio/uploadFile/stream/{fileName}")    public ResponseDTO<UploadVO> uploadStream(InputStream inputStream, @PathVariable("fileName") String fileName) throws IOException {        return filesMinioService.uploadStream(inputStream, fileName);    }     @ApiOperation(value = "文件查询(永久链接) by sunboqiang")    @GetMapping("/minio/getFileUrl/{id}")    public ResponseDTO<UploadVO> findFileById(@PathVariable("id") Long id) {        return filesMinioService.findFileById(id);    }     @ApiOperation(value = "文件流式下载 by sunboqiang")    @GetMapping("/minio/downloadFile/stream")    public ResponseEntity<byte[]> downLoadFile(@RequestParam Long id, HttpServletRequest request) {        return filesMinioService.downLoadFile(id, request);    }     @ApiOperation(value = "文件删除(通过文件名) by sunboqiang")    @PostMapping("/minio/deleteFiles")    public ResponseDTO<String> deleteFiles(@RequestBody List<String> fileNames) {        return filesMinioService.deleteFiles(fileNames);    }}

“Springboot怎么整合minio实现文件服务”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!

--结束END--

本文标题: Springboot怎么整合minio实现文件服务

本文链接: https://www.lsjlt.com/news/330879.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Springboot怎么整合minio实现文件服务
    本篇内容介绍了“Springboot怎么整合minio实现文件服务”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!首先pom文件引入相关依赖&...
    99+
    2023-06-30
  • SpringBoot 2.x怎么整合MinIo文件服务
    本篇内容主要讲解“SpringBoot 2.x怎么整合MinIo文件服务”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot 2.x怎么整合MinIo文件服务”吧!MinIO 是高...
    99+
    2023-06-03
  • SpringBoot怎么整合Minio文件存储
    这篇“SpringBoot怎么整合Minio文件存储”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringBoot怎么整...
    99+
    2023-06-29
  • Springboot整合minio实现文件服务的教程详解
    首先pom文件引入相关依赖 <!--minio--> <dependency> <groupId...
    99+
    2024-04-02
  • SpringBoot整合Minio实现上传文件的完整步骤记录
    目录Minio安装 Minio使用docker安装拉取镜像启动使用9000端口 登录控制台创建存储桶设置桶权限创建 Java 客户端依赖配置文件配置文件配置类创建 minio 客户端...
    99+
    2024-04-02
  • Java整合MinIO实现文件管理
    MinIo MinIO基于Apache License 2.0开源协议的对象存储服务。它兼容Amazon S3云存储接口。适合存储非结构化数据,如图片,音频,视频,日志等。 MinIo基础概念 Obj...
    99+
    2023-09-06
    java docker 容器
  • SpringBoot整合MinIO实现文件上传的方法详解
    目录前言1. MinIO 简介2. MinIO 安装3. 整合 Spring Boot4. 配置nginx5. 小结前言 现在 OSS 服务算是一个基础服务了,很多云服务厂商都有提供...
    99+
    2024-04-02
  • SpringBoot整合minio服务(超详细)
    一、使用docker部署minio 1、拉取镜像 docker pull minio/minio 2、创建目录 mkdir -p /home/minio/configmkdir -p /home/minio/data 3、创建Minio容器...
    99+
    2023-09-05
    spring boot minio vue
  • Springboot怎么集成minio实现文件存储
    本篇内容主要讲解“Springboot怎么集成minio实现文件存储”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Springboot怎么集成minio实现文件存储”吧!MinIO 是一款基于G...
    99+
    2023-06-29
  • SpringBoot中整合Minio文件存储的安装部署过程
    目录背景Minio安装部署配置pom文件配置yml文件Minio工具类初始化client上传文件下载文件删除文件背景 公司的开发框架集成了附件本地存储,阿里云,华为云等,现项目有要求...
    99+
    2024-04-02
  • springboot整合minio实现文件上传与下载且支持链接永久访问
    目录1、minio部署2、项目搭建3、文件上传4、文件下载5、文件永久链接下载1、minio部署 1.1 拉取镜像 docker pull minio/minio 1.2 创建数据...
    99+
    2024-04-02
  • 使用Springboot整合GridFS实现文件操作
    目录GridFsOperations,实现GridFS文件上传下载删除上传下载删除功能实现测试上传下载删除GridFsOperations,实现GridFS文件上传下载删除 最近学习...
    99+
    2024-04-02
  • SpringBoot整合EasyExcel实现文件导入导出
    目录准备工作 1. 引入pom依赖2. 实现功能 Excel文件下载 3. 日志实体类4. 接口和具体实现 Excel文件导入 5. 文件读取配置 6. 读取测试7. 附上自定义属性...
    99+
    2024-04-02
  • Python怎么实现上传Minio文件
    本篇内容介绍了“Python怎么实现上传Minio文件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!环境依赖安装minio以及oss2依赖p...
    99+
    2023-06-25
  • Springboot集成minio实现文件存储的实现代码
    目录1. 安装部署1.1 Linux 简单部署1.2 Docker 部署2. Spring boot 整合3. 问题记录4. 项目地址在我们平时做项目的时候,文件存储是个很常见的需求...
    99+
    2024-04-02
  • SpringBoot使用Minio进行文件存储的实现
    目录一、minio二、SpringBoot 使用 Minio 进行文件存储三、测试一、minio MinIO 是一个高性能的对象存储原生支持 Kubernetes 部署的解决方案。 ...
    99+
    2024-04-02
  • SpringBoot整合MongoDB实现文件上传下载删除
    目录本文主要内容 1. 基础命令 2. GridFsTemplate使用 2.1引入pom依赖2.2 配置yml2.3 上传下载删除 本文主要内容 MongoDB基础操作...
    99+
    2024-04-02
  • SpringBoot中通过AOP整合日志文件的实现
    目录1.导入相关的依赖 2.log4j2 日志文件 3.dao层的接口以及实现类 4.Service层业务实现类 5.Controller层接口控制类 6.编写业务类增强类,加入一个...
    99+
    2024-04-02
  • SpringBoot整合Javamail实现邮件发送
    博客主页:踏风彡的博客 博主介绍:一枚在学习的大学生,希望在这里和各位一起学习。 所属专栏:SpringBoot学习笔记 文章创作不易,期待各位朋友的互动,有什么学习问题都可在评论区留言或者私信我...
    99+
    2023-08-31
    spring boot java spring
  • SpringBoot整合阿里云OSS对象存储服务实现文件上传
    目录1. 准备工作: 2. 配置: 3. 详细代码: 4. 测试: 1. 准备工作: 一、首先登录阿里云OSS对象存储控制台创建一个Bucket作为你的存储空间。 二、创建Acce...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作