SpringBoot整合Minio
Spring Boot整合Minio的基本步骤如下:
- 添加Minio客户端依赖到
pom.xml
:
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>RELEASE_VERSION</version>
</dependency>
- 在
application.properties
或application.yml
中配置Minio的服务器地址、访问密钥和秘密密钥:
minio.url=http://127.0.0.1:9000
minio.access-key=your_access_key
minio.secret-key=your_secret_key
minio.bucket-name=your_bucket_name
- 创建Minio配置类:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.minio.MinioClient;
@Configuration
public class MinioConfig {
@Value("${minio.url}")
private String url;
@Value("${minio.access-key}")
private String accessKey;
@Value("${minio.secret-key}")
private String secretKey;
@Bean
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(url)
.credentials(accessKey, secretKey)
.build();
}
}
- 创建服务类来使用Minio客户端进行文件上传、下载、删除等操作:
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
@Service
public class MinioService {
@Autowired
private MinioClient minioClient;
public void uploadFile(InputStream data, String size, String fileName, String bucketName) {
try {
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.contentType("application/octet-stream")
.stream(data, data.available(), -1)
.build());
} catch (Exception e) {
e.printStackTrace();
}
}
// 其他方法(下载、删除等)
}
- 在需要上传文件的地方注入
MinioService
并调用上传方法:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@Autowired
private MinioService minioService;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
评论已关闭