注入minio客户端,其中endpoint(endpoint)
: 这里设置Minio服务器的URL;credentials(accessKey, secretKey)
: 这里设置用于认证的accessKey
和secretKey
。类似于用户名和密码。
@Bean
public MinioClient minioClient() {
return MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
}
判断桶是否存在:
BucketExistsArgs:用于创建检查特定存储桶(Bucket)是否存在的请求参数的类
boolean exists=minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
创建存储桶:
minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
删除桶:
minioClient.removeBucket(RemoveBucketArgs.builder().bucket(name).build());
单个文件上传:
public String upload(MultipartFile file){
InputStream in=null;
try{
//获取输入流
in=file.getInputStream();
minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).
object(filename).stream(in,in.available(),-1).contentType(file.getContentType()).build());
}catch (Exception e){
e.printStackTrace();
}
finally {
if (in!=null){
try {
in.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return filename;
}
下载文件:
public void download(String fileName,HttpServletResponse response){
InputStream in =null;
OutputStream out=null;
try{
out=response.getOutputStream();
in = minioClient.
getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
byte buf[]=new byte[1024];
int length=0;
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
while ((length=in.read(buf))>0){
//每次读取到数据后就写入到输入流中
out.write(buf,0,length);
}
}catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null)
out.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}