环境准备
| 依赖 | 版本 |
| Java | 1.8 |
| minio | 7.0.2 |
| maven | 3.3.9 |
| SpringBoot | 2.4 |
创建项目
完整pom文件如下
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.2</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.minio.demo</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>7.0.2</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.4.4</version></dependency><dependency><groupId>javax.persistence</groupId><artifactId>persistence-api</artifactId><version>1.0</version><scope>compile</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.73</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>
配置文件
server:port: 11808minio:endpoint: http://192.168.31.150/port: 9000accessKey: AKIAIOSFODNN7EXAMPLEsecretKey: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEYsecure: falsebucketName: "demo"
代码是之前写的demo,有一部分是参考其他博主写的代码,但由于时间有些久远,不记得是哪位博主了,因此未未能注明来源,还望抱歉,另外,以下代码经过postman测试,没什么太大的问题.不过仅供参考,请结合实际业务编写.
Minio配置类
import io.minio.MinioClient;import io.minio.errors.InvalidEndpointException;import io.minio.errors.InvalidPortException;import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.stereotype.Component;@Data@Component@ConfigurationProperties(prefix = "minio")public class MinioConfig {// endPoint是一个URL,域名,IPv4或者IPv6地址private String endpoint;// TCP/IP端口号private int port;private String accessKey;private String secretKey;// 如果是true,则用的是https而不是http,默认值是trueprivate Boolean secure;// 默认存储桶private String bucketName;@Beanpublic MinioClient getMinioClient() throws InvalidEndpointException, InvalidPortException {MinioClient minioClient = new MinioClient(endpoint, port, accessKey, secretKey, secure);return minioClient;}}
MinioService
import io.minio.ObjectStat;import io.minio.Result;import io.minio.errors.*;import io.minio.messages.Item;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;public interface MinioService {/*** 判断 bucket是否存在** @param bucketName* @return*/boolean bucketExists(String bucketName);/*** 创建 bucket** @param bucketName*/void makeBucket(String bucketName);/*** 文件上传** @param bucketName* @param objectName* @param filename*/void putObject(String bucketName, String objectName, String filename);/*** 文件上传** @param bucketName* @param objectName* @param stream*/void putObject(String bucketName, String objectName, InputStream stream, String contentType);/*** 文件上传** @param bucketName* @param multipartFile*/void putObject(String bucketName, MultipartFile multipartFile, String filename);/*** 删除文件* @param bucketName* @param objectName*/boolean removeObject(String bucketName,String objectName);/*** 下载文件** @param fileName* @param originalName* @param response*/void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response);/*** 获取文件路径* @param bucketName* @param objectName* @return*/String getObjectUrl(String bucketName,String objectName);/*** @description: 文件下载* @param: bucketNameobjectName* @return: io.minio.ObjectStat* @author yangc* @date: 2020-10-20 20:24*/ObjectStat statObject(String bucketName, String objectName);/*** 以流的形式获取一个文件对象** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @return*/InputStream getObject(String bucketName, String objectName);/*** 列出存储桶中所有对象** @param bucketName 存储桶名称* @return*/Iterable<Result<Item>> listObjects(String bucketName);/*** 生成一个给HTTP GET请求用的presigned URL** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天* @return*/String presignedGetObject(String bucketName, String objectName, Integer expires);/*** 设置存储桶策略** @param bucketName 存储桶名称* @return*/void setBucketPolicy(String bucketName, String policy) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException;/*** 获取存储桶策略** @param bucketName 存储桶名称* @return*/String getBucketPolicy(String bucketName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, BucketPolicyTooLargeException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException;}
MinioServiceIpl
import com.minio.demo.service.MinioService;import com.minio.demo.utils.MinioUtil;import io.minio.ObjectStat;import io.minio.Result;import io.minio.errors.*;import io.minio.messages.Item;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;@Servicepublic class MinioServiceImpl implements MinioService {@Autowiredprivate MinioUtil minioUtil;/*** 判断 bucket是否存在** @param bucketName* @return*/@Overridepublic boolean bucketExists(String bucketName) {return minioUtil.bucketExists(bucketName);}/*** 创建 bucket** @param bucketName*/@Overridepublic void makeBucket(String bucketName) {minioUtil.makeBucket(bucketName);}/*** 文件上传** @param bucketName* @param objectName* @param filename*/@Overridepublic void putObject(String bucketName, String objectName, String filename) {minioUtil.putObject(bucketName, objectName, filename);}@Overridepublic void putObject(String bucketName, String objectName, InputStream stream, String contentType) {minioUtil.putObject(bucketName, objectName, stream, contentType);}/*** 文件上传** @param bucketName* @param multipartFile*/@Overridepublic void putObject(String bucketName, MultipartFile multipartFile, String filename) {minioUtil.putObject(bucketName, multipartFile, filename);}/*** 删除文件* @param bucketName* @param objectName*/@Overridepublic boolean removeObject(String bucketName,String objectName) {return minioUtil.removeObject(bucketName,objectName);}/*** 下载文件** @param fileName* @param originalName* @param response*/@Overridepublic void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {minioUtil.downloadFile(bucketName,fileName, originalName, response);}/*** 获取文件路径* @param bucketName* @param objectName* @return*/@Overridepublic String getObjectUrl(String bucketName,String objectName) {return minioUtil.getObjectUrl(bucketName,objectName);}/*** @param bucketName* @param objectName* @description: 文件下载* @param: bucketName* objectName* @return: io.minio.ObjectStat* @author yangc* @date: 2020-10-20 20:24*/@Overridepublic ObjectStat statObject(String bucketName, String objectName) {return minioUtil.statObject(bucketName,objectName);}/*** 以流的形式获取一个文件对象** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @return*/@Overridepublic InputStream getObject(String bucketName, String objectName) {return minioUtil.getObject(bucketName,objectName);}/*** 列出存储桶中所有对象** @param bucketName 存储桶名称* @return*/@Overridepublic Iterable<Result<Item>> listObjects(String bucketName) {return minioUtil.listObjects(bucketName);}/*** 生成一个给HTTP GET请求用的presigned URL** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天* @return*/@Overridepublic String presignedGetObject(String bucketName, String objectName, Integer expires) {return minioUtil.presignedGetObject(bucketName, objectName, expires);}/*** 设置存储桶策略** @param bucketName 存储桶名称* @param policy* @return*/@Overridepublic void setBucketPolicy(String bucketName, String policy) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {minioUtil.setBucketPolicy(bucketName, policy);}/*** 获取存储桶策略** @param bucketName 存储桶名称* @return*/@Overridepublic String getBucketPolicy(String bucketName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, BucketPolicyTooLargeException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {return minioUtil.getBucketPolicy(bucketName);}}
MinioUtil
import io.minio.MinioClient;import io.minio.ObjectStat;import io.minio.PutObjectOptions;import io.minio.Result;import io.minio.errors.*;import io.minio.messages.Bucket;import io.minio.messages.DeleteError;import io.minio.messages.Item;import lombok.SneakyThrows;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.nio.charset.StandardCharsets;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.util.ArrayList;import java.util.List;/*** @PackageName: com.hope.minio.utils* @ClassName: MinioUtil* @Author Hope* @Date 2020/7/27 11:43* @Description: MinioUtil*/@Componentpublic class MinioUtil {@Autowiredprivate MinioClient minioClient;private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;/*** 检查存储桶是否存在** @param bucketName 存储桶名称* @return*/@SneakyThrowspublic boolean bucketExists(String bucketName) {boolean flag = false;flag = minioClient.bucketExists(bucketName);if (flag) {return true;}return false;}/*** 创建存储桶** @param bucketName 存储桶名称*/@SneakyThrowspublic boolean makeBucket(String bucketName) {boolean flag = bucketExists(bucketName);if (!flag) {minioClient.makeBucket(bucketName);return true;} else {return false;}}/*** 列出所有存储桶名称** @return*/@SneakyThrowspublic List<String> listBucketNames() {List<Bucket> bucketList = listBuckets();List<String> bucketListName = new ArrayList<>();for (Bucket bucket : bucketList) {bucketListName.add(bucket.name());}return bucketListName;}/*** 列出所有存储桶** @return*/@SneakyThrowspublic List<Bucket> listBuckets() {return minioClient.listBuckets();}/*** 删除存储桶** @param bucketName 存储桶名称* @return*/@SneakyThrowspublic boolean removeBucket(String bucketName) {boolean flag = bucketExists(bucketName);if (flag) {Iterable<Result<Item>> myObjects = listObjects(bucketName);for (Result<Item> result : myObjects) {Item item = result.get();// 有对象文件,则删除失败if (item.size() > 0) {return false;}}// 删除存储桶,注意,只有存储桶为空时才能删除成功。minioClient.removeBucket(bucketName);flag = bucketExists(bucketName);if (!flag) {return true;}}return false;}/*** 列出存储桶中的所有对象名称** @param bucketName 存储桶名称* @return*/@SneakyThrowspublic List<String> listObjectNames(String bucketName) {List<String> listObjectNames = new ArrayList<>();boolean flag = bucketExists(bucketName);if (flag) {Iterable<Result<Item>> myObjects = listObjects(bucketName);for (Result<Item> result : myObjects) {Item item = result.get();listObjectNames.add(item.objectName());}}return listObjectNames;}/*** 列出存储桶中的所有对象** @param bucketName 存储桶名称* @return*/@SneakyThrowspublic Iterable<Result<Item>> listObjects(String bucketName) {boolean flag = bucketExists(bucketName);if (flag) {return minioClient.listObjects(bucketName);}return null;}/*** 通过文件上传到对象** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @param fileName File name* @return*/@SneakyThrowspublic boolean putObject(String bucketName, String objectName, String fileName) {boolean flag = bucketExists(bucketName);if (flag) {minioClient.putObject(bucketName, objectName, fileName, null);ObjectStat statObject = statObject(bucketName, objectName);if (statObject != null && statObject.length() > 0) {return true;}}return false;}/*** 文件上传** @param bucketName* @param multipartFile*/@SneakyThrowspublic void putObject(String bucketName, MultipartFile multipartFile, String filename) {PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);putObjectOptions.setContentType(multipartFile.getContentType());minioClient.putObject(bucketName, filename, multipartFile.getInputStream(), putObjectOptions);}/*** 通过InputStream上传对象** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @param stream 要上传的流* @param stream 要上传的文件类型 MimeTypeUtils.IMAGE_JPEG_VALUE* @return*/@SneakyThrowspublic boolean putObject(String bucketName, String objectName, InputStream stream,String contentType) {boolean flag = bucketExists(bucketName);if (flag) {PutObjectOptions putObjectOptions = new PutObjectOptions(stream.available(), -1);/*** 开启公共类功能设置setContentType*/if (StringUtils.isNotBlank(contentType)) {putObjectOptions.setContentType(contentType);}minioClient.putObject(bucketName, objectName, stream, putObjectOptions);ObjectStat statObject = statObject(bucketName, objectName);if (statObject != null && statObject.length() > 0) {return true;}}return false;}/*** 以流的形式获取一个文件对象** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @return*/@SneakyThrowspublic InputStream getObject(String bucketName, String objectName) {boolean flag = bucketExists(bucketName);if (flag) {ObjectStat statObject = statObject(bucketName, objectName);if (statObject != null && statObject.length() > 0) {InputStream stream = minioClient.getObject(bucketName, objectName);return stream;}}return null;}/*** 以流的形式获取一个文件对象(断点下载)** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @param offset 起始字节的位置* @param length 要读取的长度 (可选,如果无值则代表读到文件结尾)* @return*/@SneakyThrowspublic InputStream getObject(String bucketName, String objectName, long offset, Long length) {boolean flag = bucketExists(bucketName);if (flag) {ObjectStat statObject = statObject(bucketName, objectName);if (statObject != null && statObject.length() > 0) {InputStream stream = minioClient.getObject(bucketName, objectName, offset, length);return stream;}}return null;}/*** 下载并将文件保存到本地** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @param fileName File name* @return*/@SneakyThrowspublic boolean getObject(String bucketName, String objectName, String fileName) {boolean flag = bucketExists(bucketName);if (flag) {ObjectStat statObject = statObject(bucketName, objectName);if (statObject != null && statObject.length() > 0) {minioClient.getObject(bucketName, objectName, fileName);return true;}}return false;}/*** 删除一个对象** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称*/@SneakyThrowspublic boolean removeObject(String bucketName, String objectName) {boolean flag = bucketExists(bucketName);if (flag) {minioClient.removeObject(bucketName, objectName);return true;}return false;}/*** 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表** @param bucketName 存储桶名称* @param objectNames 含有要删除的多个object名称的迭代器对象* @return*/@SneakyThrowspublic List<String> removeObject(String bucketName, List<String> objectNames) {List<String> deleteErrorNames = new ArrayList<>();boolean flag = bucketExists(bucketName);if (flag) {Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);for (Result<DeleteError> result : results) {DeleteError error = result.get();deleteErrorNames.add(error.objectName());}}return deleteErrorNames;}/*** 生成一个给HTTP GET请求用的presigned URL。* 浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天* @return*/@SneakyThrowspublic String presignedGetObject(String bucketName, String objectName, Integer expires) {boolean flag = bucketExists(bucketName);String url = "";if (flag) {if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {throw new InvalidExpiresRangeException(expires,"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);}url = minioClient.presignedGetObject(bucketName, objectName, expires);}return url;}/*** 生成一个给HTTP PUT请求用的presigned URL。* 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天* @return*/@SneakyThrowspublic String presignedPutObject(String bucketName, String objectName, Integer expires) {boolean flag = bucketExists(bucketName);String url = "";if (flag) {if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {throw new InvalidExpiresRangeException(expires,"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);}url = minioClient.presignedPutObject(bucketName, objectName, expires);}return url;}/*** 获取对象的元数据** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @return*/@SneakyThrowspublic ObjectStat statObject(String bucketName, String objectName) {boolean flag = bucketExists(bucketName);if (flag) {ObjectStat statObject = minioClient.statObject(bucketName, objectName);return statObject;}return null;}/*** 文件访问路径** @param bucketName 存储桶名称* @param objectName 存储桶里的对象名称* @return*/@SneakyThrowspublic String getObjectUrl(String bucketName, String objectName) {boolean flag = bucketExists(bucketName);String url = "";if (flag) {url = minioClient.getObjectUrl(bucketName, objectName);}return url;}/*** 设置存储桶策略** @param bucketName 存储桶名称* @param policy 存储桶里的对象名称*/public void setBucketPolicy(String bucketName, String policy) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {minioClient.setBucketPolicy(bucketName, policy);}/*** 获取存储桶策略** @param bucketName 存储桶名称* @return*/public String getBucketPolicy(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, BucketPolicyTooLargeException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException {return minioClient.getBucketPolicy(bucketName);}public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {try {InputStream file = minioClient.getObject(bucketName, fileName);String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);if (StringUtils.isNotEmpty(originalName)) {fileName = originalName;}response.setHeader("Content-Disposition", "attachment;filename=" + filename);ServletOutputStream servletOutputStream = response.getOutputStream();int len;byte[] buffer = new byte[1024];while ((len = file.read(buffer)) > 0) {servletOutputStream.write(buffer, 0, len);}servletOutputStream.flush();file.close();servletOutputStream.close();} catch (ErrorResponseException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}}
MinioController
import com.alibaba.fastjson.JSON;import com.minio.demo.config.MinioConfig;import com.minio.demo.result.Result;import com.minio.demo.service.MinioService;import com.minio.demo.utils.UploadFile;import io.minio.ObjectStat;import io.minio.errors.*;import io.minio.messages.Item;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;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.IOException;import java.io.InputStream;import java.net.URLEncoder;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.text.DecimalFormat;import java.util.*;@RequestMapping("/minio")@RestController@Slf4jpublic class MinioController {@Autowiredprivate MinioService minioService;@Autowiredprivate MinioConfig minioConfig;@Autowiredprivate UploadFile uploadFile;@SneakyThrows@PostMapping("/file")public Result uploadFile(MultipartFile file, @RequestParam("bucketName") String bucketName) {uploadFile.uploadFile(file, bucketName);return Result.success();}@PostMapping("/files")public Result uploadFiles(@RequestParam("multipartFiles") List<MultipartFile> files, @RequestParam("bucketName") String bucketName) {for (MultipartFile file : files) {uploadFile.uploadFile(file, bucketName);}return Result.success();}@GetMapping("/file")public Result download(HttpServletResponse response, @RequestParam("fileName") String fileName, @RequestParam("bucketName") String bucketName, @RequestParam("fileId") String fileId) {try {//获取存储捅名bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();//获取对象信息和对象的元数据。ObjectStat objectStat = minioService.statObject(bucketName, fileName);//setContentType 设置发送到客户机的响应的内容类型response.setContentType(objectStat.contentType());//设置响应头response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectStat.name(), "UTF-8"));//文件流InputStream object = minioService.getObject(bucketName, fileName);//设置文件大小response.setHeader("Content-Length", String.valueOf(objectStat.length()));IOUtils.copy(object, response.getOutputStream());//关闭流object.close();return Result.success();} catch (Exception e) {log.error("下载文件失败,错误信息: " + e.getMessage());return Result.fail("下载失败.");}}@DeleteMapping(value = "/file")public Result deleteFile(@RequestParam("bucketName") String bucketName, @RequestParam("objectName") String objectName) {minioService.removeObject(bucketName, objectName);return Result.success();}@GetMapping(value = "/file/list")public Result<List<Object>> getFileList(@RequestParam("bucketName") String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {try {//获取存储捅名bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();//列出存储桶中所有对象Iterable<io.minio.Result<Item>> results = minioService.listObjects(bucketName);//迭代器Iterator<io.minio.Result<Item>> iterator = results.iterator();List<Object> items = new ArrayList<>();String format = "{'fileName':'%s','fileSize':'%s'}";while (iterator.hasNext()) {//返回迭代中的下一个元素。Item item = iterator.next().get();//封装信息items.add(JSON.parse(String.format(format, "http://localhost:9000/"+bucketName+"/"+item.objectName(), formatFileSize(item.size()))));}return Result.success(items);} catch (Exception e) {log.error("获取文件列表失败,错误信息: " + e.getMessage());return Result.fail("获取文件列表失败");}}@GetMapping("/preview/file")public Result<List<Object>> getPreviewFile(@RequestParam("bucketName") String bucketName,@RequestParam("expires") Integer expires,@RequestParam("objectName") String objectName) {//获取存储捅名bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();//生成一个给HTTP GET请求用的presigned URLString filePath = minioService.presignedGetObject(bucketName, objectName, expires);//封装信息return Result.success(filePath);}@GetMapping("/previewList")public Result<List<Object>> getPreviewList(@RequestParam("bucketName") String bucketName,@RequestParam("expires") Integer expires) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {try {//获取存储捅名bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();//列出存储桶中所有对象Iterable<io.minio.Result<Item>> myObjects = minioService.listObjects(bucketName);//迭代器Iterator<io.minio.Result<Item>> iterator = myObjects.iterator();List<Object> items = new ArrayList<>();String format = "{'fileName':'%s','fileSize':'%s'}";while (iterator.hasNext()) {//返回迭代中的下一个元素。Item item = iterator.next().get();//生成一个给HTTP GET请求用的presigned URLString filePath = minioService.presignedGetObject(bucketName, item.objectName(), expires);//封装信息items.add(JSON.parse(String.format(format, filePath, formatFileSize(item.size()))));}return Result.success(items);} catch (Exception e) {return Result.fail("生成可以预览的文件链接失败,错误信息:" + e.getMessage());}}/*** 显示文件大小信息单位** @param fileS* @return*/private static String formatFileSize(long fileS) {DecimalFormat df = new DecimalFormat("#.00");String fileSizeString = "";String wrongSize = "0B";if (fileS == 0) {return wrongSize;}if (fileS < 1024) {fileSizeString = df.format((double) fileS) + " B";} else if (fileS < 1048576) {fileSizeString = df.format((double) fileS / 1024) + " KB";} else if (fileS < 1073741824) {fileSizeString = df.format((double) fileS / 1048576) + " MB";} else {fileSizeString = df.format((double) fileS / 1073741824) + " GB";}return fileSizeString;}}
UploadFile
import cn.hutool.core.io.file.FileNameUtil;import com.minio.demo.config.MinioConfig;import com.minio.demo.service.MinioService;import lombok.SneakyThrows;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.multipart.MultipartFile;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;@Componentpublic class UploadFile {@Autowiredprivate MinioService minioService;@Autowiredprivate MinioConfig minioConfig;@SneakyThrowspublic void uploadFile(MultipartFile file, String bucketName) {// 获取存储桶名称,不存在则使用默认桶名bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();// 判断是否存在该存储桶if (!minioService.bucketExists(bucketName)) {// 不存在则创建minioService.makeBucket(bucketName);// 设置存储桶只读策略String bucketPolicy ="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"" +"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::fast\"]},{\"Effect\":\"Allow\",\"" +"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" +bucketName+"/*\"]}]}";// 设置存储桶策略minioService.setBucketPolicy(bucketName,bucketPolicy);}// 原始文件名String fileName = file.getOriginalFilename();// 获取文件后缀名String extName = FileNameUtil.extName(fileName);// 定义文件路径String format = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());// 定义文件修改之后的名字,去除uuid中的' - 'String fileuuid = UUID.randomUUID().toString().replaceAll("-", "");// 定义新的文件名String objectName = format + fileuuid + "." + extName;//上传文件minioService.putObject(bucketName, file, objectName);}}
测试
单个文件上传


多文件上传


文件下载

文件删除

生成可以预览的链接

生成单个可预览的链接

demo仓库地址
为方面大家查看,已经将代码上传到码云上,地址如下:
https://gitee.com/cyangDrow/min-iodemo/tree/master
文章转载自风雪留客,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




