注意
minio 新版本有9000和9090两个端口,web访问是9000,但走api上传和访问都是9090端口
引入pom
<dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>8.2.0</version></dependency>
controller
@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();}
}