本文主要介绍使用minio的javasdk处理上传和下载业务。
一、pom.xml的依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--MINIO-->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.3.4</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
二、minioclient的初始化
public void init(){
minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
}
三、minio上传数据
@Test
public void upload(){
File file = new File("/Users/shenyunsese/Desktop/pic3.png");
String objectName="test/pic3.png";
try {
FileInputStream fileInputStream=new FileInputStream(file);
minioClient.putObject(PutObjectArgs.builder().bucket(bucket)
.object(objectName)
.contentType("image/png")
.stream(fileInputStream, fileInputStream.available(), -1).build());
}catch (Exception e){
e.printStackTrace();
}
System.out.println("finished");
}
四、minio下载数据
@Test
public void download(){
String objectName="test/pic3.png";
String fileName="/Users/shenyunsese/Desktop/download2.png";
try {
StatObjectResponse response = minioClient.statObject(
StatObjectArgs.builder().bucket(bucket).object(objectName).build()
);
if (response != null) {
minioClient.downloadObject(DownloadObjectArgs.builder()
.bucket(bucket)
.object(objectName)
.filename(fileName)
.build());
}
}catch (Exception e){
e.printStackTrace();
}
System.out.println("finished");
}
五、完整的代码
package test.minio;
import io.minio.*;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
public class MinioOpTest {
private String endpoint ="http://192.168.75.117:9000";
private String accessKey="something";
private String secretKey="somethingkey";
private String bucket="images";
private MinioClient minioClient;
@Before
public void init(){
minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
}
@Test
public void upload(){
File file = new File("/Users/shenyunsese/Desktop/pic3.png");
String objectName="test/pic3.png";
try {
FileInputStream fileInputStream=new FileInputStream(file);
minioClient.putObject(PutObjectArgs.builder().bucket(bucket)
.object(objectName)
.contentType("image/png")
.stream(fileInputStream, fileInputStream.available(), -1).build());
}catch (Exception e){
e.printStackTrace();
}
System.out.println("finished");
}
@Test
public void download(){
String objectName="test/pic3.png";
String fileName="/Users/shenyunsese/Desktop/download2.png";
try {
StatObjectResponse response = minioClient.statObject(
StatObjectArgs.builder().bucket(bucket).object(objectName).build()
);
if (response != null) {
minioClient.downloadObject(DownloadObjectArgs.builder()
.bucket(bucket)
.object(objectName)
.filename(fileName)
.build());
}
}catch (Exception e){
e.printStackTrace();
}
System.out.println("finished");
}
}