1. Download and start the minio file server
https://dl.min.io/server/minio/release/windows-amd64/minio.exe
Start the minio file server
minio.exe server D:\Photos
Visit localhost:9000, enter minioadmin, minioadmin login successfully, you can see the following interface:
Two, add dependencies
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>3.0.10</version>
</dependency>
Three, write code minioController
package com.dzx.blogsystem.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.StreamProgress;
import com.dzx.blogsystem.util.JsonReponse;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author 80004819
* @ClassName:
* @Description:
* @date 2020年10月04日 12:12:09
*/
@RestController
@RequestMapping("/minio")
@Slf4j
@Api(tags = "minio文件服务接口")
public class MinIoController {
public static MinioClient minioClient;
public static String bucketName;
static {
try {
minioClient = new MinioClient("http://localhost:9000",
"minioadmin",
"minioadmin");
bucketName = "test";
} catch (InvalidEndpointException e) {
e.printStackTrace();
} catch (InvalidPortException e) {
e.printStackTrace();
}
}
@PostMapping("/uploadFile")
@ApiOperation("上传文件")
public JsonReponse uploadFile(@RequestParam("file") MultipartFile file) {
try {
String originalFilename = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
String contentType = file.getContentType();
minioClient.putObject(bucketName, originalFilename, inputStream, contentType);
return JsonReponse.success("上传成功");
} catch (Exception e) {
log.error("上传文件异常", e);
return JsonReponse.fail("上传失败");
}
}
@GetMapping("/downloadFile")
@ApiOperation("下载文件")
public void downloadFile(@RequestParam("fileName") String fileName, HttpServletResponse response) {
try {
InputStream is = minioClient.getObject(bucketName, fileName);
fileName = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
IoUtil.copyByNIO(is, response.getOutputStream(), 10240, new StreamProgress() {
@Override
public void start() {
log.info("开始下载");
}
@Override
public void progress(long l) {
log.info("下载进度:{}", l);
}
@Override
public void finish() {
log.info("下载完成!");
}
});
// return JsonReponse.success("下载成功");
} catch (Exception e) {
log.error("上传文件异常", e);
// return JsonReponse.fail("上传失败");
}
}
@GetMapping("/getFileUrl")
@ApiOperation("获取文件下载地址")
public JsonReponse getFileUrl(@RequestParam("fileName") String fileName) {
try {
//下载地址
String s1 = minioClient.presignedGetObject(bucketName, fileName);
String s2 = minioClient.getObjectUrl(bucketName, fileName);
String s3 = minioClient.getPresignedObjectUrl(Method.GET, bucketName, fileName, 80000, null);
log.info("s1-{}", s1);
log.info("s2-{}", s2);
log.info("s3-{}", s3);
return JsonReponse.success(s1);
} catch (Exception e) {
log.error("获取文件下载地址异常", e);
return JsonReponse.fail("获取文件下载地址失败");
}
}
@GetMapping("/testMinioApi")
@ApiOperation("测试minio文件服务器api")
public void testMinioApi() {
try {
//判断桶是否存在
boolean myBucket = minioClient.bucketExists("my-bucket");
if (!myBucket) {
//获取桶列表
List<Bucket> buckets = minioClient.listBuckets();
buckets.forEach(bucket -> {
log.info("桶名:{},创建日期:{}", bucket.name(), DateUtil.format(bucket.creationDate(), "yyyy-MM-dd HH:mm:ss"));
});
//创建桶
minioClient.makeBucket("my-bucket");
//上传文件
minioClient.putObject("my-bucket", "JDK_API_1_6_zh_CN.CHM", "C:\\Users\\ASUS\\Desktop\\[Java参考文档]JDK_API_1_6_zh_CN.CHM");
ObjectStat objectStat = minioClient.statObject("my-bucket", "JDK_API_1_6_zh_CN.CHM");
log.info("objectStat名称:{}", objectStat.name());
// Map<String, PolicyType> map = minioClient.getBucketPolicy("my-bucket");
// map.forEach((s, policyType) -> {
// log.info("s{},policyType{}",s,policyType);
// });
}
//移除对象和桶
if (minioClient.bucketExists("test")) {
List<String> objectStrs = new ArrayList<>();
minioClient.listObjects("test").forEach(itemResult -> {
try {
objectStrs.add(itemResult.get().objectName());
} catch (Exception e) {
e.printStackTrace();
}
});
minioClient.removeObject("test", objectStrs);
minioClient.removeBucket("test");
}
} catch (Exception e) {
log.error("error", e);
}
}
}
Note: The naming of the bucket needs to meet the Amazon s3 standard
Amazon S3 bucket naming requirements
The name of the Amazon S3 bucket used to store CloudTrail log files must meet the naming requirements of non-US standard regions. The naming of Amazon S3 buckets must comply with one or more of the following rules (separated by periods):
-
The bucket name can be between 3 and 63 characters long, and can only contain lowercase letters, numbers, periods, and dashes.
-
Each label in the bucket name must start with a lowercase letter or number.
-
The bucket name cannot contain an underscore, end with a dash, contain consecutive periods, or use a dash next to the period.
-
The bucket name cannot be in the IP address format (198.51.100.24).