springboot集成minIO

前置课程:Dockercompose搭建minIO文件服务器以及简单使用

1. 引入依赖
<minio.version>7.1.0</minio.version>

<!-- minio -->
 <dependency>
     <groupId>io.minio</groupId>
     <artifactId>minio</artifactId>
     <version>${minio.version}</version>
 </dependency>
2. yml配置
# minio 连接参数
minio:
  url: http://ip:port  // ip和端口号
  accessKey: tomato	// 账号
  secretKey: tomato123 // 密码
  bucketName: blog	// bucket名
#  preview-expiry: 24 //图片预览过期时间 不需要可注掉
3. config文件
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinIOConfig {
    /**
     * 服务地址
     */
    private String url;

    /**
     * 用户名
     */
    private String accessKey;

    /**
     * 密码
     */
    private String secretKey;

    /**
     * 存储桶名称
     */
    private String bucketName;

    /**
     * 预览到期时间(小时)
     */
    private Integer previewExpiry;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public Integer getPreviewExpiry() {
        return previewExpiry;
    }

    public void setPreviewExpiry(Integer previewExpiry) {
        this.previewExpiry = previewExpiry;
    }

    @Bean
    public MinioClient getMinIOClient()
    {
        return MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
    }
}

4. 实体类
public class FileVo implements Serializable {
    private String fileName;
    private String previewUrl;
    /**
     * 所属模块(转换为"桶")
     */
    private String module;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getPreviewUrl() {
        return previewUrl;
    }

    public void setPreviewUrl(String previewUrl) {
        this.previewUrl = previewUrl;
    }

    public String getModule() {
        return module;
    }

    public void setModule(String module) {
        this.module = module;
    }
}
public class FileUploadBody implements Serializable {
    /**
     * 多文件
     */
    private MultipartFile[] files;
    /**
     * 所属模块(转换为"桶")
     */
    private String module;
    /**
     * 自定义文件名
     */
    private String fileName;

    public MultipartFile[] getFiles() {
        return files;
    }

    public void setFiles(MultipartFile[] files) {
        this.files = files;
    }

    public String getModule() {
        return module;
    }

    public void setModule(String module) {
        this.module = module;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}
5. service
public interface MinIOFileService {
    List<FileVo> uploadFile(FileUploadBody body);

    String getPreviewUrl(String fileName, String bucketName);

    void downloadFile(HttpServletResponse response, String fileName, String bucketName);

    String delFile(String fileName, String bucketName);
}
@Service
@Slf4j
public class MinIOFileServiceImpl implements MinIOFileService {

    @Autowired
    private MinIOConfig minIOConfig;
    @Autowired
    private MinioClient minioClient;

    @Override
    public List<FileVo> uploadFile(FileUploadBody body){
        MultipartFile[] files=body.getFiles();
        if (Objects.nonNull(files) && files.length > 0) {
            String bucketName = StringUtils.isNotBlank(body.getModule()) ? body.getModule().replaceAll(",", "") : minIOConfig.getBucketName();
            List<FileVo> resultList = new ArrayList<>();
            for (MultipartFile file : files) {
                try {
                    log.info("file: " + file);
                    if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                        minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                    }
                    String fileName = file.getOriginalFilename();
                    if (StringUtils.isNotBlank(body.getFileName())){
                        fileName = body.getFileName();
                    }
                    StringBuffer fileNameSB = new StringBuffer();
                    fileNameSB.append(System.currentTimeMillis()).append("_").append(bucketName).append("_");
                    if (StringUtils.isNotBlank(fileName)){
                        fileNameSB.append(fileName.replaceAll(",", ""));
                    }
                    fileName = fileNameSB.toString();
                    PutObjectArgs args = PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build();
                    minioClient.putObject(args);
                    FileVo fileVo=new FileVo();
                    fileVo.setFileName(fileName);
                    fileVo.setModule(bucketName);
                    fileVo.setPreviewUrl(getPreviewUrl(fileName,bucketName));
                    resultList.add(fileVo);
                }catch (Exception e){
                    log.info("上传图片失败:",e.getMessage());
                }
            }
            return resultList;
        }
        return Collections.emptyList();
    }

    @Override
    public String getPreviewUrl(String fileName, String bucketName) {
        if (StringUtils.isNotBlank(fileName)) {
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minIOConfig.getBucketName();
            try {
                minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
                if (null != minIOConfig.getPreviewExpiry()){
                    return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket(bucketName).object(fileName).expiry(minIOConfig.getPreviewExpiry(), TimeUnit.HOURS).build());
                }else {
                    return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket(bucketName).object(fileName).build());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void downloadFile(HttpServletResponse response, String fileName, String bucketName) {
        if (StringUtils.isNotBlank(fileName)) {
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minIOConfig.getBucketName();
            try {
                ObjectStat objectStat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType(objectStat.contentType());
                response.setCharacterEncoding("UTF-8");
                InputStream inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
                IOUtils.copy(inputStream, response.getOutputStream());
            } catch (Exception e) {
            }
        }
    }

    @Override
    public String delFile(String fileName, String bucketName) {
        if (StringUtils.isNotBlank(fileName)) {
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minIOConfig.getBucketName();
            try {
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
                return "success";
            }catch (Exception e) {
                return "删除文件失败,请刷新后重试";
            }
        }
        return "文件不能为空";
    }
}


6. controller
@RestController
@RequestMapping("minIO")
public class UploadTestController {

    private final MinIOFileService fileService;

    public UploadTestController(MinIOFileService fileService) {
        this.fileService = fileService;
    }


    @PostMapping("/upload")
    public Result<?> uploadTest(FileUploadBody body) {
        List<FileVo> list;
        try {
            list = fileService.uploadFile(body);
        } catch (Exception e) {
            return Result.fail("上传失败,请刷新后重试!");
        }
        return ObjectUtils.isNull(list) ? Result.fail("上传文件不能为空") : Result.ok(list,"上传成功");
    }
}
7. 测试

在这里插入图片描述

成功上传到bucket中😊
返回的previewUrl就是预览图片

永久访问

如上图所示的previewUrl,这个url非常的长,且设置有的访问时效,默认7天
如果我们想通过http://localhost:xx/bucketName/image.jpg 这种方式去访问,需要对bucket进行设置:
在这里插入图片描述

添加对应规则后便可直接访问图片

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐