springboot集成文件上传到服务器本地进行加密后存储到 Minio
- application.yml配置信息
yunnuo:
profile: D:/tsms/uploadPath
minio:
endpoint: http://localhost:9000
accesskey: minioadmin
secretkey: minioadmin
bucketName: backfile
- pom文件依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
minio集成
- MinioProp.java 实体类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProp {
private String endpoint;
private String accesskey;
private String secretkey;
private String bucketName;
@Override
public String toString() {
return "MinioProp{" +
"endpoint='" + endpoint + '\'' +
", accesskey='" + accesskey + '\'' +
", secretkey='" + secretkey + '\'' +
", bucketName='" + bucketName + '\'' +
'}';
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
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;
}
}
- MinioConfig 配置类
package com.tsms.common.config.minio;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(MinioProp.class)
@Slf4j
public class MinioConfig {
@Autowired
private MinioProp minioProp;
@Bean
public MinioClient minioClient() {
try {
log.info("minioClient create start");
MinioClient minioClient = MinioClient.builder().endpoint(minioProp.getEndpoint()).credentials(minioProp.getAccesskey(), minioProp.getSecretkey())
.build();
log.info("minioClient create end");
return minioClient;
} catch (Exception e) {
log.error("连接MinIO服务器异常:{}", e);
return null;
}
}
}
- MinioUtils 工具类
import com.alibaba.fastjson.JSONObject;
import com.dpms.business.minio.MinioProp;
import com.dpms.common.utils.StringUtils;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
@Component
@Slf4j
public class MinioUtils {
@Autowired
private MinioProp minioProp;
private MinioClient minioClient;
@PostConstruct
private MinioClient client() {
try {
log.info("minioClient create start");
minioClient = MinioClient.builder().endpoint(minioProp.getEndpoint()).credentials(minioProp.getAccesskey(), minioProp.getSecretkey())
.build();
log.info("minioClient create end");
createBucket();
} catch (Exception e) {
log.error("连接MinIO服务器异常:{}", e);
}
return minioClient;
}
public void createBucket(String bucketName) {
try {
if (!client().bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
} catch (Exception e) {
log.error("创建桶失败:{}", e);
}
}
private void createBucket()
throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException, RegionConflictException {
if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProp.getBucketName()).build())) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProp.getBucketName()).build());
}
}
public boolean doesObjectExist(String bucketName, String objectName) {
boolean exist = true;
try {
minioClient
.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
exist = false;
}
return exist;
}
public boolean doesFolderExist(String bucketName, String objectName) {
boolean exist = false;
try {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());
for (Result<Item> result : results) {
Item item = result.get();
if (item.isDir() && objectName.equals(item.objectName())) {
exist = true;
}
}
} catch (Exception e) {
exist = false;
}
return exist;
}
public ObjectWriteResponse putObject(String bucketName, MultipartFile file,
String objectName, String contentType)
throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
InputStream inputStream = file.getInputStream();
return minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
.stream(
inputStream, inputStream.available(), -1)
.build());
}
public ObjectWriteResponse putObject(String bucketName, String objectName,
String fileName)
throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
return minioClient.uploadObject(
UploadObjectArgs.builder()
.bucket(bucketName).object(objectName).filename(fileName).build());
}
public ObjectWriteResponse putObjectbyStream(String bucketName, String objectName,
InputStream inputStream)
throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
return minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
inputStream, inputStream.available(), -1)
.build());
}
public ObjectWriteResponse putDirObject(String bucketName, String objectName)
throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
return minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
new ByteArrayInputStream(new byte[]{}), 0, -1)
.build());
}
public JSONObject uploadFile(MultipartFile file, String bucketName) throws Exception {
JSONObject res = new JSONObject();
res.put("code", 0);
if (null == file || 0 == file.getSize()) {
res.put("msg", "上传文件不能为空");
return res;
}
createBucket(bucketName);
String originalFilename = file.getOriginalFilename();
String fileName = bucketName + "_" +
System.currentTimeMillis() +
originalFilename.substring(originalFilename.lastIndexOf("."));
putObjectbyStream(bucketName, fileName, file.getInputStream());
res.put("code", 1);
res.put("fileName", fileName);
res.put("msg", minioProp.getEndpoint() + "/" + bucketName + "/" + fileName);
return res;
}
public JSONObject uploadFile(String filepath, String uuid, String bucketName) throws Exception {
File oldFile = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(oldFile);
JSONObject res = new JSONObject();
res.put("code", 0);
if (StringUtils.isNull(oldFile)) {
res.put("msg", "上传文件不能为空");
return res;
}
createBucket(bucketName);
String originalFilename = oldFile.getName();
String fileName = bucketName + "_" +
System.currentTimeMillis() + "_" + uuid +
originalFilename.substring(originalFilename.lastIndexOf("."));
putObjectbyStream(bucketName, fileName, fileInputStream);
res.put("code", 1);
res.put("fileName", fileName);
res.put("msg", minioProp.getEndpoint() + "/" + bucketName + "/" + fileName);
return res;
}
public JSONObject uploadFile(String filepath, String bucketName) throws Exception {
File oldFile = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(oldFile);
JSONObject res = new JSONObject();
res.put("code", 0);
if (StringUtils.isNull(oldFile)) {
res.put("msg", "上传文件不能为空");
return res;
}
createBucket(bucketName);
String originalFilename = oldFile.getName();
String fileName = bucketName + "_" +
System.currentTimeMillis() +
originalFilename.substring(originalFilename.lastIndexOf("."));
putObjectbyStream(bucketName, fileName, fileInputStream);
res.put("code", 1);
res.put("fileName", fileName);
res.put("msg", minioProp.getEndpoint() + "/" + bucketName + "/" + fileName);
return res;
}
public List<Bucket> getAllBuckets() throws Exception {
return client().listBuckets();
}
public void removeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
}
public String getObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
return client().presignedGetObject(bucketName, objectName, expires);
}
public InputStream getObject(String bucketName, String objectName) throws Exception {
return client().getObject(bucketName, objectName);
}
public void putObject(String bucketName, String objectName, InputStream stream) throws
Exception {
putObjectbyStream(bucketName,objectName,stream);
}
public void putObject(String bucketName, String objectName, InputStream stream, long
size, String contextType) throws Exception {
putObjectbyStream(bucketName,objectName,stream);
}
public ObjectStat getObjectInfo(String bucketName, String objectName) throws Exception {
return client().statObject(bucketName, objectName);
}
public void removeObject(String bucketName, String objectName) throws Exception {
client().removeObject(bucketName, objectName);
}
}
- controller测试
@Autowired
private MinioProp minioProp;
@Autowired
private MinioUtils minioUtils;
@PostMapping("/uploadFile")
@ResponseBody
public List<FileUploadLog> uploadFile(@RequestParam(value = "files", required = true) MultipartFile[] files) {
for (MultipartFile file : files) {
minioUtils.upload(file,minioProp.getBucketName);
}
}