当前位置:

首页 > 编程开发 > Springboot怎么整合minio实现文件服务

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

首先pom文件引入相关依赖io.miniominio3.0.10springboot配置文件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_

本文目录

    首先pom文件引入相关依赖

            
            
                io.minio
                minio
                3.0.10
            

    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;
     
    @Data
    public class MinioItem {
        /**对象名称**/
        @ApiModelProperty("对象名称")
        private String objectName;
        /**最后操作时间**/
        @ApiModelProperty("最后操作时间")
        private Date lastModified;
        private String etag;
        /**对象大小**/
        @ApiModelProperty("对象大小")
        private String size;
        private String storageClass;
        private Owner owner;
        /**对象类型:directory(目录)或file(文件)**/
        @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
    @RequiredArgsConstructor
    public class MinioTemplate implements InitializingBean {
     
        /**
         * minio的路径
         **/
        @Value("${minio.endpoint}")
        private String endpoint;
     
        /**
         * minio的accessKey
         **/
        @Value("${minio.accessKey}")
        private String accessKey;
     
        /**
         * minio的secretKey
         **/
        @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);
        }
     
        /**
         * 创建bucket
         *
         * @param bucketName bucket名称
         */
        @SneakyThrows
        public void createBucket(String bucketName) {
            if (!bucketExists(bucketName)) {
                minioClient.makeBucket(bucketName);
            }
        }
     
        /**
         * 获取全部bucket
         * 

         * https://docs.minio.io/cn/java-client-api-reference.html#listBuckets      */     @SneakyThrows     public List getAllBuckets() {         return minioClient.listBuckets();     }       /**      * 根据bucketName获取信息      *      * @param bucketName bucket名称      */     @SneakyThrows     public Optional getBucket(String bucketName) {         return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();     }       /**      * 根据bucketName删除信息      *      * @param bucketName bucket名称      */     @SneakyThrows     public void removeBucket(String bucketName) {         minioClient.removeBucket(bucketName);     }       /**      * 根据文件前缀查询文件      *      * @param bucketName bucket名称      * @param prefix     前缀      * @param recursive  是否递归查询      * @return MinioItem 列表      */     @SneakyThrows     public List getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {         List objectList = new ArrayList<>();         Iterable> objectsIterator = minioClient.listObjects(bucketName, prefix, recursive);         for (Result result : objectsIterator) {             objectList.add(new MinioItem(result.get()));         }         return objectList;     }       /**      * 获取文件外链      *      * @param bucketName bucket名称      * @param objectName 文件名称      * @param expires    过期时间 <=7      * @return url      */     @SneakyThrows     public String getObjectURL(String bucketName, String objectName, Integer expires) {         return minioClient.presignedGetObject(bucketName, objectName, expires);     }       /**      * 获取文件外链      *      * @param bucketName bucket名称      * @param objectName 文件名称      * @return url      */     @SneakyThrows     public String getObjectURL(String bucketName, String objectName) {         return minioClient.presignedGetObject(bucketName, objectName);     }       /**      * 获取文件url地址      *      * @param bucketName bucket名称      * @param objectName 文件名称      * @return url      */     @SneakyThrows     public String getObjectUrl(String bucketName, String objectName) {         return minioClient.getObjectUrl(bucketName, objectName);     }       /**      * 获取文件      *      * @param bucketName bucket名称      * @param objectName 文件名称      * @return 二进制流      */     @SneakyThrows     public InputStream getObject(String bucketName, String objectName) {         return minioClient.getObject(bucketName, objectName);     }       /**      * 上传文件(流下载)      *      * @param bucketName bucket名称      * @param objectName 文件名称      * @param stream     文件流      * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject      */     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);     }       /**      * 上传文件      *      * @param bucketName  bucket名称      * @param objectName  文件名称      * @param stream      文件流      * @param size        大小      * @param contextType 类型      * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject      */     public void putObject(String bucketName, String objectName, InputStream stream, long size, String contextType) throws Exception {         minioClient.putObject(bucketName, objectName, stream, size, contextType);     }       /**      * 获取文件信息      *      * @param bucketName bucket名称      * @param objectName 文件名称      * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#statObject      */     public ObjectStat getObjectInfo(String bucketName, String objectName) throws Exception {         return minioClient.statObject(bucketName, objectName);     }       /**      * 删除文件夹及文件      *      * @param bucketName bucket名称      * @param objectName 文件或文件夹名称      * @since tarzan LIU      */     public void removeObject(String bucketName, String objectName) {         try {             if (StringUtils.isNotBlank(objectName)) {                 if (objectName.endsWith(".") || objectName.endsWith("/")) {                     Iterable> 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();         }     }       /**      * 下载文件夹内容到指定目录      *      * @param bucketName bucket名称      * @param objectName 文件或文件夹名称      * @param dirPath    指定文件夹路径      * @since tarzan LIU      */     public void downloadTargetDir(String bucketName, String objectName, String dirPath) {         try {             if (StringUtils.isNotBlank(objectName)) {                 if (objectName.endsWith(".") || objectName.endsWith("/")) {                     Iterable> 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> list = minioClient.listObjects("spacedata", "CompileResult/");             List 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);         }     }       /**      * 文件流下载(原始文件名)      *      * @author sunboqiang      * @date 2020/10/22      */     public ResponseEntity 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 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 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
    @Slf4j
    public class FilesMinioService extends ServiceImpl {
     
        @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());
        }
     
        /**
         * 验证文件大小
         *
         * @param upfile
         * @param fileName 文件名称
         * @throws Exception
         */
        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限制");
                }
            }
        }
     
        /**
         * 文件上传
         *
         * @author sunboqiang
         * @date 2020/9/9
         */
        public ResponseDTO 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 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);
        }
     
        /**
         * 生成文件名字
         * 当前年月日时分秒 +32位 uuid + 文件格式后缀
         *
         * @param originalFileName
         * @return String
         */
        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;
        }
     
        /**
         * 文件上传(不做重复校验)
         *
         * @author sunboqiang
         * @date 2020/9/25
         */
        public ResponseDTO 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);
        }
     
        /**
         * 文件流上传(不存数据库)
         *
         * @author sunboqiang
         * @date 2020/9/25
         */
        public ResponseDTO 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;
        }
     
        /**
         * 文件查询
         *
         * @author sunboqiang
         * @date 2020/9/25
         */
        public ResponseDTO findFileById(Long id) {
            FileEntity fileEntity = baseMapper.selectById(id);
            if (null == fileEntity) {
                return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM, "文件不存在");
            }
            UploadVO vo = new UploadVO();
            /*String url = minioTemplate.getObjectURL(bucket,fileEntity.getFileName());
            if(StringUtils.isEmpty(url)){
                return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"获取minio 文件url失败!");
            }*/
            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);
        }
     
     
        /**
         * 文件流式下载
         *
         * @author sunboqiang
         * @date 2020/10/22
         */
        public ResponseEntity 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 stream = minioTemplate.fileDownload(httpUrl + fileEntity.getFileUrl(), fileEntity.getOriginalFileName(), request);
            return stream;
        }
     
        /**
         * 文件删除(通过文件名)
         *
         * @author tarzan Liu
         * @date 2020/11/11
         */
        public ResponseDTO deleteFiles(List fileNames) {
            try {
                for (String fileName : fileNames) {
                    minioTemplate.removeObject(bucket, fileName);
                }
            } catch (Exception e) {
                return ResponseDTO.wrap(ResponseCodeConst.ERROR, e.getMessage());
            }
            return ResponseDTO.succ();
        }
     
        /**
         * tarzan LIU
         *
         * @author tarzan Liu
         * @date 2020/11/11
         */
        public ResponseDTO downloadTargetDir(String objectName, String dirPath) {
            minioTemplate.downloadTargetDir(bucket, objectName, dirPath);
            return ResponseDTO.succ();
        }
     
        /**
         * 下载备份编译结果
         *
         * @param dirPath
         * @return {@link Boolean}
         * @author zhangpeng
         * @date 2021年10月15日
         */
        public Boolean downloadCompile(String dirPath) {
            if (!minioTemplate.bucketExists(bucket)) {
                log.info("Bucket not exists.");
                return true;
            }
     
            List 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文件服务"})
    @RestController
    public class FilesMinioController {
     
        @Autowired
        private FilesMinioService filesMinioService;
     
     
        @ApiOperation(value = "文件上传(md5去重上传) by sunboqiang")
        @PostMapping("/minio/uploadFile/md5")
        @NoNeedLogin
        public ResponseDTO uploadFile(MultipartFile file) throws IOException {
            return filesMinioService.fileUpload(file);
        }
     
        @ApiOperation(value = "文件上传(不做重复校验) by sunboqiang")
        @PostMapping("/minio/uploadFile/noRepeatCheck")
        public ResponseDTO fileUploadRep(MultipartFile file) throws IOException {
            return filesMinioService.fileUploadRep(file);
        }
     
        @ApiOperation(value = "文件流上传 by sunboqiang")
        @PostMapping("/minio/uploadFile/stream/{fileName}")
        public ResponseDTO uploadStream(InputStream inputStream, @PathVariable("fileName") String fileName) throws IOException {
            return filesMinioService.uploadStream(inputStream, fileName);
        }
     
        @ApiOperation(value = "文件查询(永久链接) by sunboqiang")
        @GetMapping("/minio/getFileUrl/{id}")
        public ResponseDTO findFileById(@PathVariable("id") Long id) {
            return filesMinioService.findFileById(id);
        }
     
        @ApiOperation(value = "文件流式下载 by sunboqiang")
        @GetMapping("/minio/downloadFile/stream")
        public ResponseEntity downLoadFile(@RequestParam Long id, HttpServletRequest request) {
            return filesMinioService.downLoadFile(id, request);
        }
     
        @ApiOperation(value = "文件删除(通过文件名) by sunboqiang")
        @PostMapping("/minio/deleteFiles")
        public ResponseDTO deleteFiles(@RequestBody List fileNames) {
            return filesMinioService.deleteFiles(fileNames);
        }
    }
    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发
    相关文章 更多
    Windows下Minio安装与使用教程
    Windows下Minio安装与使用教程

    Windows下Minio的安装以及基本使用Minio是什么?Minio是一个开源的、云原生的分布式对象存储系统,是一个基于ApacheLicensev2.0开源协议的对象存储服务。它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据。它一大特点就是轻量,虽然轻量,却拥有着不错的性能。使用简单,功能强大,支持各种平台,单个文件最大5TB,兼容AmazonS3接口,提供了Java、Python、GO等多版本SDK支持。官网:https://www.minio.org.cn接下来我们介

    springBoot项目常用目录有哪些
    springBoot项目常用目录有哪些

    springBoot项目常用目录springBoot项目的目录结构及名规范介绍基于SpringBoot开发时的目录结构及命名规范,通过介绍能够为你解决,在实际项目中如何规划目录结构?如何命名目录更规范?各个目录分别代表什么含义?等三个问题。目录说明servicex//项目名|-admin-ui//管理服务前端代码(一般将UI和SERVICE放到一个工程中,便于管理)|-servicex-auth//模块1|-servicex-common//模块2|-servicex-gateway//模块3|-serv

    使用PHP搭建MinIO分布式对象存储系统
    使用PHP搭建MinIO分布式对象存储系统

    随着云计算和大数据技术的发展,越来越多的企业和组织开始关注数据存储和处理的问题。传统的存储方案显然已经无法满足现代技术的需求,因此分布式对象存储成为了一个备受关注的话题。分布式对象存储的核心思想是将数据分散存储在多个节点上,通过智能的负载均衡和数据备份,实现更高效、更安全的数据管理。在开源领域中,MinIO是一个备受推崇的分布式对象存储实现方案之一,本文将介

    解析SpringBoot和SpringMVC之间的异同
    解析SpringBoot和SpringMVC之间的异同

    解析SpringBoot和SpringMVC之间的异同SpringBoot和SpringMVC是Java领域中非常重要的开发框架。虽然它们都属于Spring框架的一部分,但是在使用和功能上有一些明显的区别。本文将对SpringBoot和SpringMVC进行比较,解析它们之间的异同。首先,让我们来了解一下SpringBoot。SpringBo

    探索SpringCloud和SpringBoot在微服务领域的不同应用方式
    探索SpringCloud和SpringBoot在微服务领域的不同应用方式

    近年来,随着云计算和分布式架构的兴起,微服务架构的应用越来越广泛。而SpringCloud和SpringBoot作为Java开发中的两个重要框架,对于微服务的实现起到了重要的作用。然而,很多人对于它们在微服务领域的不同应用方式还存在一定的疑惑。本文将从不同的角度探索SpringCloud和SpringBoot在微服务中的应用方式。首先,我们来了解一下Spri

    SpringBoot和SpringMVC有何区别?
    SpringBoot和SpringMVC有何区别?

    SpringBoot与SpringMVC的不同之处在哪里?SpringBoot和SpringMVC是两个非常流行的Java开发框架,用于构建Web应用程序。尽管它们经常分别被使用,但它们之间的不同之处也是很明显的。首先,SpringBoot可以被看作是一个Spring框架的扩展或者增强版。它旨在简化Spring应用程序的初始化和配置过程,以帮助开发人

    比较SpringBoot和SpringMVC的异同
    比较SpringBoot和SpringMVC的异同

    SpringBoot和SpringMVC都是Java开发中常用的框架,但它们之间有一些明显的差异。本文将探究这两个框架的特点和用途,并对它们的差异进行比较。首先,我们来了解一下SpringBoot。SpringBoot是由Pivotal团队开发的,它旨在简化基于Spring框架的应用程序的创建和部署。它提供了一种快速、轻量级的方式来构建独立的、可执行

    SpringBoot与SpringMVC的不同点是什么?
    SpringBoot与SpringMVC的不同点是什么?

    SpringBoot和SpringMVC是Java开发中常用的两个框架,它们都是由Spring框架所提供的,但在功能和使用方式上有着一些区别。本文将分别介绍SpringBoot和SpringMVC的特点和区别。一、SpringBoot的特点:简化配置:SpringBoot通过约定优于配置的原则,大大简化了项目的配置过程。它可以自动配置项目所需要的参数,开发人

    比较和选择指南:SpringCloud与SpringBoot的功能比较
    比较和选择指南:SpringCloud与SpringBoot的功能比较

    SpringCloud和SpringBoot是目前Java领域中最热门的开源框架,它们分别提供了一套完善的微服务架构和快速构建应用程序的解决方案。本文将对它们的功能进行比较,并给出选择指南,以帮助读者了解它们的优势和适用场景。SpringBoot是一个用于开发Java应用程序的框架,它提供了一个简化的开发流程,集成了大量常用的功能和组件,减少了开发者的工作量

    SpringCloud与SpringBoot:分析它们之间的相似与不同
    SpringCloud与SpringBoot:分析它们之间的相似与不同

    深入剖析SpringCloud和SpringBoot的异同引言:在构建企业级应用程序时,Spring框架已经成为开发者们的首选。它提供了一种简单而强大的方式来构建独立于平台的应用程序。Spring框架由两个核心模块组成:SpringBoot和SpringCloud。虽然它们都可以帮助开发者快速搭建应用程序,但它们的目标和用途存在一些差异。本文将深入剖析Spr

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。