文章目录
Minio Java Client使用
MinIO Java Client SDK提供简单的API来访问任何与Amazon S3兼容的对象存储服务。
官方文档:https://min.io/docs/minio/linux/developers/java/API.html
Spring项目
引入依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.3.0</version>
</dependency>
<dependency>
<groupId>me.tongfei</groupId>
<artifactId>progressbar</artifactId>
<version>0.5.3</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.8.1</version>
</dependency>
文件上传
public class FileUploader {
public static void main(String[] args)
throws IOException, NoSuchAlgorithmException, InvalidKeyException {
try {
// Create a minioClient with the MinIO server playground, its access key and secret key.
MinioClient minioClient = MinioClient.builder().endpoint("http://192.168.3.14:9000").credentials("admin", "12345678").build();
// 创建bucket
String bucketName = "tulingmall";
boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (!exists) { // 不存在,创建bucket
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
// 上传文件
minioClient.uploadObject( UploadObjectArgs.builder()
.bucket(bucketName)
.object("tuling-mall-master.zip")
.filename("F:\\mall\\tuling-mall-master.zip")
.build()
);
System.out.println("上传文件成功");
} catch (MinioException e) {
System.out.println("Error occurred: " + e);
System.out.println("HTTP trace: " + e.httpTrace());
}
}
}
文件下载
public class DownLoadDemo {
public static void main(String[] args) {
// Create a minioClient with the MinIO server playground, its access key and secret key.
MinioClient minioClient = MinioClient.builder().endpoint("http://192.168.3.14:9000").credentials("admin", "12345678").build();
// Download object given the bucket, object name and output file name
try {
minioClient.downloadObject( DownloadObjectArgs.builder()
.bucket("tulingmall")
.object("fox/fox.jpg")
.filename("fox.jpg")
.build()
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
SpringBoot项目
构建MinioClient对象,并交给spring管理
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {
private String endpoint;
private String accessKey;
private String secretKey;
}
yml文件添加相关配置信息
minio:
endpoint: http://192.168.3.14:9000
accesskey: admin
secretKey: 12345678
创建Minio配置类
@Configuration
public class MinioConfig {
@Autowired
private MinioProperties minioProperties;
@Bean
public MinioClient minioClient(){
MinioClient minioClient = MinioClient.builder()
.endpoint(minioProperties.getEndpoint())
.credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
.build();
return minioClient;
}
}
进行文件的上传、下载和删除
@RestController
@Slf4j
public class MinioController {
@Autowired
private MinioClient minioClient;
@Value("${minio.bucketName}")
private String bucketName;
@GetMapping("/list")
public List<Object> list() throws Exception {
//获取bucket列表
Iterable<Result<Item>> myObjects = minioClient.listObjects(
ListObjectsArgs.builder()
.bucket(bucketName)
.build()
);
Iterator<Result<Item>> iterator = myObjects.iterator();
List<Object> items = new ArrayList<>();
String format = "{'fileName':'%s','fileSize':'%s'}";
while (iterator.hasNext()) {
Item item = iterator.next().get();
items.add(
JSON.parse(String.format(
format, item.objectName(),
formatFileSize(item.size())
)
)
);
}
return items;
}
@PostMapping("/upload")
public Res upload(@RequestParam(name = "file", required = false) MultipartFile[] file) {
if (file == null || file.length == 0) {
return Res.error("上传文件不能为空");
}
List<String> orgfileNameList = new ArrayList<>(file.length);
for (MultipartFile multipartFile : file) {
String orgfileName = multipartFile.getOriginalFilename();
orgfileNameList.add(orgfileName);
try {
//文件上传
InputStream in = multipartFile.getInputStream();
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(orgfileName)
.stream(in, multipartFile.getSize(), -1)
.contentType(multipartFile.getContentType())
.build());
in.close();
} catch (Exception e) {
log.error(e.getMessage());
return Res.error("上传失败");
}
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("bucketName", bucketName);
data.put("fileName", orgfileNameList);
return Res.ok("上传成功",data);
}
@RequestMapping("/download/{fileName}")
public void download(HttpServletResponse response, @PathVariable("fileName") String fileName) {
InputStream in = null;
try {
// 获取对象信息
StatObjectResponse stat = minioClient.statObject(
StatObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build()
);
response.setContentType(stat.contentType());
response.setHeader(
"Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")
);
//文件下载
in = minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build()
);
IOUtils.copy(
in,
response.getOutputStream()
);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
}
@DeleteMapping("/delete/{fileName}")
public Res delete(@PathVariable("fileName") String fileName) {
try {
minioClient.removeObject(
RemoveObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build()
);
} catch (Exception e) {
log.error(e.getMessage());
return Res.error("删除失败");
}
return Res.ok("删除成功",null);
}
private static String formatFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
} if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + " B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + " KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + " MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + " GB";
}
return fileSizeString;
}
}