注意
minio 新版本有9000和9090两个端口,web访问是9000,但走api上传和访问都是9090端口
引入pom文章来源:https://www.toymoban.com/news/detail-809581.html
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.0</version>
</dependency>
controller文章来源地址https://www.toymoban.com/news/detail-809581.html
@PostMapping("uploadMinio")
public static String uploadMinio(@RequestParam("file") MultipartFile multipartFile){
try{
return MinioUtil.upload(multipartFile);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
MinioUtil
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class MinioUtil {
// 替换为你的MinIO服务器地址、端口、访问密钥和秘密密钥
private static final String endpoint = "http://localhost:9090";
private static final String accessKey = "xxx";
private static final String secretKey = "xxx";
private static final String bucketName = "xxx";
private static final String host = "http://localhost:9090/" + bucketName + "/";
public static String upload(MultipartFile multipartFile) throws IOException {
InputStream inputStream = null;
try {
MinioClient minioClient = MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
// 获取文件后缀
String suffix = getFileExtension(multipartFile.getOriginalFilename());
if (StringUtils.isBlank(suffix)) {
return "";
}
// 修改 objectName 为正确的文件名 + 后缀
String objectName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
inputStream = convertMultipartFileToInputStream(multipartFile);
// 检查存储桶是否存在,如果不存在则创建
if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
// 上传文件
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.stream(inputStream, multipartFile.getSize(), -1)
.contentType("application/octet-stream") // 设置文件类型
.build());
return host + objectName; // 返回上传后的对象名
} catch (IOException | XmlParserException | ServerException | NoSuchAlgorithmException |
InsufficientDataException | InvalidKeyException | InvalidResponseException |
ErrorResponseException | InternalException e) {
return null;
} finally {
inputStream.close();
}
}
public static String getFileExtension(String filePath) {
int lastDotIndex = filePath.lastIndexOf(".");
if (lastDotIndex > 0) {
return filePath.substring(lastDotIndex + 1);
}
return ""; // 如果找不到点或没有后缀,则返回空字符串
}
public static InputStream convertMultipartFileToInputStream(MultipartFile multipartFile) throws IOException {
return multipartFile.getInputStream();
}
}
到了这里,关于springboot minio 工具类,一站式解决的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!