前期准备
需要先安装minio文件服务器,请参考我上一篇文章
pom.xml 版本
本次使用的是springboot2.7.16 版本,
minio 版本是8.2.2
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.16</version><relativePath/></parent><dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>8.2.2</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.11</version></dependency>
配置minio服务
minio.endpoint=**********
minio.accessKey=******
minio.secretKey=*******
minio.bucketName=shuangningzixun
# 单个文件上传的最大值
spring.servlet.mutipart.max-file-size=200MB
# 整个请求体上传的文件大小
spring.servlet.mutipart.max-request-size=500MB
其中endpoint 为本地安装的minio服务地址,形式为IP+端口
accessKey和secretKey为用户名密码
桶名称则是在minio服务上新增的桶名称。
minio配置类
package com.example.demo.config;import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MinioConfig {/*** 访问地址*/@Value("${minio.endpoint}")private String endpoint;/*** accessKey类似于用户ID,用于唯一标识你的账户*/@Value("${minio.accessKey}")private String accessKey;/*** secretKey是你账户的密码*/@Value("${minio.secretKey}")private String secretKey;/*** 默认存储桶*/@Value("${minio.bucketName}")private String bucketName;@Beanpublic MinioClient minioClient() {MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();return minioClient;}
}
minio配置实体类
package com.example.demo.config;import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@ConfigurationProperties(prefix="minio")
@Component
@Getter
@Setter
public class Minio {private String url;private String username;private String password;private String bucketName;}
minio下载服务类
package com.example.demo.service;import com.example.demo.config.Minio;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;@Component
public class MinioService {@Autowiredprivate MinioClient minioClient;@Autowiredprivate Minio minio;public String uploadFile(MultipartFile file) throws IOException {//判断捅是否存在String url=null;try {boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minio.getBucketName()).build());if (!bucketExists){//如果不存在,就创建捅minioClient.makeBucket(MakeBucketArgs.builder().bucket(minio.getBucketName()).build());}String yyyyMMdd = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-mm-dd"));String uuid = UUID.randomUUID().toString();String filename = yyyyMMdd +"/"+file.getOriginalFilename();//minioClient.putObject(PutObjectArgs.builder().bucket(minio.getBucketName()).object(uuid).stream(file.getInputStream(),file.getSize(),-1).contentType(file.getContentType()).build());url = minio.getUrl()+"/"+minio.getBucketName()+"/"+filename;return url;} catch (Exception e) {}finally {file.getInputStream().close();}return url;}
}
minio 上传文件工具类
package com.example.demo.utils;import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.io.InputStream;@Component
public class MinioUtils {@Autowiredprivate MinioClient minioClient;public InputStream getObject(String bucketName, String objectName) throws Exception {return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());}
}
文件控制器
package com.example.demo.controller;import com.example.demo.common.ApiResult;
import com.example.demo.config.Minio;
import com.example.demo.service.MinioService;
import com.example.demo.utils.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {@Autowiredprivate MinioService minioService;@Autowiredprivate MinioUtils minioUtils;@Autowiredprivate Minio minio;/*** 文件上传接口*/@PostMapping("/upload")public ApiResult<Void> upload(@RequestParam("file")MultipartFile multipartFile) throws Exception{minioService.uploadFile(multipartFile);return null;}/*** 文件下载接口*/@GetMapping("/download")public void download(@RequestParam("fileName")String fileName,HttpServletResponse response) {try {InputStream fileInputStream = minioUtils.getObject(minio.getBucketName(),fileName);response.setHeader("Content-Disposition","attachment;filename="+fileName);response.setContentType("application/force-download");response.setCharacterEncoding("UTF-8");IOUtils.copy(fileInputStream,response.getOutputStream());} catch (Exception e) {log.info("下载失败",e);}}
}
postman测试
可以在minio控制台查询到已经上传的文件。
到此一个简单的文件上传下载服务就算成功了