Minio 文件服务器搭建并与springboot 整合
Minio 文件服务器介绍
MinIO是为性能和s3 api而设计的,100%开源。MinIO是具有严格安全性的大型私有云环境的理想选择
要求并提供跨各种工作负载的关键任务可用性。
https://min.io/
Minio 文件服务器搭建
推荐使用docker 部署minio
从docker 仓库中下载minio镜像
docker pull minio/minio
docker run -p 9000:9000 --name minio
-d --restart=always
-e “MINIO_ACCESS_KEY= XXXXXX”
-e “MINIO_SECRET_KEY=XXXXXXXXXX”
-v /home/data:/data
-v /home/config:/root/.minio
minio/minio server /data
-d --restart=always \ //docker 服务重启的之后 容器也会重新启动
-e “MINIO_ACCESS_KEY=admin” \ //环境变量
-v /home/data:/data \ //挂载文件路径
容器正常启动后可以使用 http://XXXXXXX:9000 访问minio 服务器
通过Web 端可以右下叫的 + 按钮可以添加存储桶,设定存储桶的访问权限。
可以往存储桶中上传文件,可以分享访问链接
客户端使用
docker仓库中下载minio 客户端镜像
docker pull minio/mc
启动容器
docker run -it --entrypoint=/bin/sh minio/mc
客户端的使用参照官网说明
https://docs.min.io/docs/minio-client-quickstart-guide.html
Spring boot 整合
maven 依赖包引入
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.1.0</version>
</dependency>
#minio配置
minio:
endpoint: http://服务器地址:9000/
accessKey: XXXXX
secretKey: XXXXXXXX
bucketName: joy //存储桶名称
配置类
package com.joy.springboot.config;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
private String endpoint;
private String accessKey;
private String secretKey;
@Bean
public MinioClient getMinioClient(){
MinioClient minioClient = MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey,secretKey)
.build();
return minioClient;
}
}
minio 工具类
package com.joy.springboot.utils;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class MinioUtil {
@Autowired
private MinioClient minioClient;
private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
/**
* 检查存储桶是否存在
*
* @param bucketName 存储桶名称
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public boolean bucketExists(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName)
.build());
if (flag) {
return true;
}
return false;
}
/**
* 创建存储桶
*
* @param bucketName 存储桶名称
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
* @throws RegionConflictException
*/
public boolean makeBucket(String bucketName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException, RegionConflictException {
boolean flag = bucketExists(bucketName);
if (!flag) {
minioClient.makeBucket(
MakeBucketArgs.builder()
.bucket(bucketName)
.build());
return true;
} else {
return false;
}
}
/**
* 列出所有存储桶名称
*
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public List<String> listBucketNames() throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
List<Bucket> bucketList = listBuckets();
List<String> bucketListName = new ArrayList<>();
for (Bucket bucket : bucketList) {
bucketListName.add(bucket.name());
}
return bucketListName;
}
/**
* 列出所有存储桶
*
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public List<Bucket> listBuckets() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
return minioClient.listBuckets();
}
/**
* 删除存储桶
*
* @param bucketName 存储桶名称
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public boolean removeBucket(String bucketName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
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(RemoveBucketArgs.builder().bucket(bucketName).build());
flag = bucketExists(bucketName);
if (!flag) {
return true;
}
}
return false;
}
/**
* 列出存储桶中的所有对象名称
*
* @param bucketName 存储桶名称
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public List<String> listObjectNames(String bucketName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
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
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public Iterable<Result<Item>> listObjects(String bucketName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
}
return null;
}
/**
* 通过InputStream上传对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param stream 要上传的流
* @param contentType 上传文件的格式,若是不设定格式默认都是application/octet-stream, 浏览器访问直接下载
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public boolean putObject(String bucketName, String objectName, InputStream stream, String contentType) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.putObject( PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
stream, stream.available(), -1)
.contentType(contentType)
.build());
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 以流的形式获取一个文件对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public InputStream getObject(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
return stream;
}
}
return null;
}
/**
* 以流的形式获取一个文件对象(断点下载)
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param offset 起始字节的位置
* @param length 要读取的长度 (可选,如果无值则代表读到文件结尾)
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
return stream;
}
}
return null;
}
/**
* 下载并将文件保存到本地
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public boolean getObject(String bucketName, String objectName, String fileName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
return true;
}
}
return false;
}
/**
* 删除一个对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public boolean removeObject(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.removeObject(RemoveObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
return true;
}
return false;
}
/**
* 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
*
* @param bucketName 存储桶名称
* @param objects 含有要删除的多个object名称的迭代器对象
* @return
* @throws InvalidKeyException
* @throws ErrorResponseException
* @throws IllegalArgumentException
* @throws InsufficientDataException
* @throws InternalException
* @throws InvalidBucketNameException
* @throws InvalidResponseException
* @throws NoSuchAlgorithmException
* @throws XmlParserException
* @throws IOException
*/
public List<String> removeObject(String bucketName, List<DeleteObject> objects) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder()
.bucket(bucketName)
.objects(objects)
.build());
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
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
* @throws InvalidExpiresRangeException
*/
public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException, InvalidExpiresRangeException {
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.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucketName)
.object(objectName)
.expiry(expires)
.build());
}
return url;
}
/**
* 生成一个给HTTP PUT请求用的presigned URL。
* 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return
* @throws InvalidKeyException
* @throws ErrorResponseException
* @throws IllegalArgumentException
* @throws InsufficientDataException
* @throws InternalException
* @throws InvalidBucketNameException
* @throws InvalidResponseException
* @throws NoSuchAlgorithmException
* @throws XmlParserException
* @throws IOException
* @throws InvalidExpiresRangeException
*/
public String getPresignedObjectGetPutUrl(String bucketName, String objectName, Integer expires) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException, InvalidExpiresRangeException {
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);
}
Map<String, String> reqParams = new HashMap<String, String>();
reqParams.put("response-content-type", "application/json");
url = minioClient.getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
.method(Method.PUT)
.bucket(bucketName)
.object(objectName)
.expiry(expires)
.extraQueryParams(reqParams)
.build());
}
return url;
}
/**
* 获取对象的元数据
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public ObjectStat statObject(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = minioClient.statObject(StatObjectArgs.builder()
.bucket(bucketName)
.object(objectName).build());
return statObject;
}
return null;
}
/**
* 文件访问路径
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
* @throws IOException
* @throws XmlParserException
* @throws NoSuchAlgorithmException
* @throws InvalidResponseException
* @throws InvalidBucketNameException
* @throws InternalException
* @throws InsufficientDataException
* @throws IllegalArgumentException
* @throws ErrorResponseException
* @throws InvalidKeyException
*/
public String getObjectUrl(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
url = minioClient.getObjectUrl(bucketName, objectName);
}
return url;
}
/**
* 设定存储桶策略
* @param bucketName
* @param policyJson
* @throws IOException
* @throws InvalidKeyException
* @throws InvalidResponseException
* @throws InsufficientDataException
* @throws NoSuchAlgorithmException
* @throws ServerException
* @throws InternalException
* @throws XmlParserException
* @throws InvalidBucketNameException
* @throws ErrorResponseException
*/
public void setBucketPolicy(String bucketName, String policyJson) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
minioClient.setBucketPolicy(
SetBucketPolicyArgs.builder()
.bucket(bucketName)
.config(policyJson)
.build());
}
}
上传下载
package com.joy.springboot.controller;
import com.joy.springboot.utils.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
@RestController
public class MinioController {
@Autowired
private MinioUtil minioUtil;
@Value("${minio.bucketName}")
private String bucketName;
/**
* 创建储存桶
* @param bucketName
*/
public void CreateBucket(String bucketName){
/*policy 的设定可以参照aws 中文档说明*/
/*https://docs.aws.amazon.com/AmazonS3/latest/dev/access-policy-language-overview.html*/
StringBuilder policyJsonBuilder = new StringBuilder();
policyJsonBuilder.append("{\n");
policyJsonBuilder.append(" \"Statement\": [\n");
policyJsonBuilder.append(" {\n");
policyJsonBuilder.append(" \"Action\": [\n");
policyJsonBuilder.append(" \"s3:GetBucketLocation\",\n");
policyJsonBuilder.append(" \"s3:ListBucket\"\n");
policyJsonBuilder.append(" ],\n");
policyJsonBuilder.append(" \"Effect\": \"Allow\",\n");
policyJsonBuilder.append(" \"Principal\": \"*\",\n");
policyJsonBuilder.append(" \"Resource\": \"arn:aws:s3:::"+bucketName+"\"\n");
policyJsonBuilder.append(" },\n");
policyJsonBuilder.append(" {\n");
policyJsonBuilder.append(" \"Action\": \"s3:GetObject\",\n");
policyJsonBuilder.append(" \"Effect\": \"Allow\",\n");
policyJsonBuilder.append(" \"Principal\": \"*\",\n");
policyJsonBuilder.append(" \"Resource\": \"arn:aws:s3:::"+bucketName+"/project-file*\"\n");
policyJsonBuilder.append(" }\n");
policyJsonBuilder.append(" ],\n");
policyJsonBuilder.append(" \"Version\": \"2012-10-17\"\n");
policyJsonBuilder.append("}\n");
try {
minioUtil.makeBucket(bucketName);
minioUtil.setBucketPolicy(bucketName, policyJsonBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建存储桶失败:" + e.getMessage());
}
}
/**
* 文件上传接口
* @param file 上传的文件对象
* @return 上传成功返回文件url 图片 txt 文件支持通过url 浏览器直接预览
*/
@PostMapping("/upload")
public String MinIOUpload(MultipartFile file) {
if (file.isEmpty() || file.getSize() == 0) {
return "文件为空";
}
try {
if (!minioUtil.bucketExists(bucketName)) {
CreateBucket(bucketName);
}
String fileName = file.getOriginalFilename();
String newName = "project-file/" + UUID.randomUUID().toString().replaceAll("-", "")
+ fileName.substring(fileName.lastIndexOf("."));
InputStream inputStream = file.getInputStream();
minioUtil.putObject(bucketName, newName, inputStream, file.getContentType());
inputStream.close();
String url = minioUtil.getObjectUrl(bucketName, newName);
return url;
} catch (Exception e) {
e.printStackTrace();
return "上传失败";
}
}
/**
* 文件下载
* @param filename 文件名
* @param httpResponse 接口返回对象
*/
@GetMapping("download/{filename}")
public void downloadFiles(@PathVariable("filename") String filename, HttpServletResponse httpResponse) {
try {
InputStream object = minioUtil.getObject(bucketName, "/project-file/"+filename);
byte buf[] = new byte[1024];
int length = 0;
httpResponse.reset();
httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
httpResponse.setContentType("application/octet-stream");
httpResponse.setCharacterEncoding("utf-8");
OutputStream outputStream = httpResponse.getOutputStream();
while ((length = object.read(buf)) > 0) {
outputStream.write(buf, 0, length);
}
outputStream.close();
} catch (Exception ex) {
System.out.println("文件下载失败:" + ex.getMessage());
}
}
}
使用postman 上传文件,上传成功返回访问URL
通过URL可以浏览器直接访问文件
遇到奇葩问题
搭建好Minio服务器后,提供同事项目使用,他们将我提供Demo 运行后,postman 请求上传文件出现时间格式错误问题
java.time.format.DateTimeParseException: Text '20200821T102419Z' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2020-08-21T10:24:19 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1919)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1854)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:596)
at io.minio.Signer.signV4(Signer.java:297)
at io.minio.MinioClient.execute(MinioClient.java:984)
at io.minio.MinioClient.execute(MinioClient.java:935)
at io.minio.MinioClient.executeHead(MinioClient.java:1204)
at io.minio.MinioClient.bucketExists(MinioClient.java:3592)
at com.joy.springbootminio.springbootminio.utils.MinioUtil.bucketExists(MinioUtil.java:48)
at com.joy.springbootminio.springbootminio.controller.MinioController.MinIOUpload(MinioController.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.ja
在判断存储桶是否存在的时候抛出以上异常,发生错误的原因是,HTTP访问文件服务器的时候,构建request 的时候需要设定Header 参数 requestBuilder.header(“x-amz-date”, date.format(Time.AMZ_DATE_FORMAT));这里时间格式问题导致的。
判断是否docker 中的时间格式有问题,于是进入minio 服务端容器中,通过date 命令查看发现时间是UTC
1.复制相应的时区文件,替换系统时区文件;
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
有的容器基础镜像是有这个文件的,直接拷贝就可以,如果不能拷贝,则是因为创建镜像时依赖的基础镜像 运行的容器没有这两个文件,使用下面的办法
- 创建文件夹
mkdir -p /usr/share/zoneinfo/Asia
3.回到宿主机,复制宿主机里的文件到容器中
docker cp /usr/share/zoneinfo/Asia/Shanghai 容器ID或容器名:/usr/share/zoneinfo/Asia
- 进入容器
docker exec -it 容器Id或容器名 /bin/sh
执行命令 cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
- 验证date
结果还是遇到同样的问题。。。。。…。。。…。。.。…。。
最后想到若是时间格式问题,应该是大家都是出现同样的问题。于是考虑环境的不同, 发现我使用的JDK是 1.8.0_261 , 同事使用的是1.8.0_05. 所以果断让他们更新JDK版本, 结果完美解决。