minio 上传MultipartFile
时间: 2023-06-21 09:24:59 浏览: 169
你好!使用MinIO SDK可以很容易地上传MultipartFile。以下是一个示例,假设你已经创建了一个MinIO的客户端(参考官方文档):
```java
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.web.multipart.MultipartFile;
public class MinioUploader {
private final MinioClient minioClient;
public MinioUploader(MinioClient minioClient) {
this.minioClient = minioClient;
}
public void upload(MultipartFile file, String bucketName, String objectName) throws Exception {
try {
PutObjectArgs args = PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.stream(file.getInputStream(), file.getSize(), -1) // 上传文件的流和大小
.contentType(file.getContentType()) // 设置文件类型
.build();
minioClient.putObject(args);
} catch (MinioException e) {
throw new Exception("Failed to upload file " + objectName + " to bucket " + bucketName, e);
}
}
public byte[] download(String bucketName, String objectName) throws Exception {
try {
GetObjectArgs args = GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build();
return minioClient.getObject(args).readAllBytes();
} catch (MinioException e) {
throw new Exception("Failed to download file " + objectName + " from bucket " + bucketName, e);
}
}
}
```
在上面的示例中,上传的文件是从`MultipartFile`对象中获取的。`stream(file.getInputStream(), file.getSize(), -1)`用于指定上传文件的流和大小。`contentType(file.getContentType())`用于设置文件类型。你可以根据自己的需要修改这些选项。
阅读全文