windows 服务端下载地址
https://dl.minio.io/server/minio/release/windows-amd64/minio.exe
安装启动
在cmd窗口中,命令行进行minio.exe所在的文件夹,输入如下命令 server后面的地址是你图片上传之后的存储目录
.\minio.exe server E:\minio
访问默认ip地址http://localhost:9000/minio/login,默认账号密码都是minioadmin
Java客户端
首先创建一个Springboot项目,在resources中的application.yml文件添加如下配置:
server:
port: 8080
spring:
servlet:
multipart:
enabled: true #开启文件上传
max-file-size: 500MB
max-request-size: 500MB
minio:
endpoint: http://localhost:9000 #Minio服务所在地址
bucketName: tcc #存储桶名称
accessKey: tanchuntcc #访问的key
secretKey: tanchuntcc #访问的秘钥
添加minio的maven依赖:
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>3.0.10</version>
</dependency>
controller的代码如下:
@RestController("/minioDemo")
public class MinioDemoController {
private static final Logger LOGGER = LoggerFactory.getLogger(MinioDemoController.class);
@Value("${minio.endpoint}")
private String ENDPOINT;
@Value("${minio.bucketName}")
private String BUCKETNAME;
@Value("${minio.accessKey}")
private String ACCESSKEY;
@Value("${minio.secretKey}")
private String SECRETKEY;
//文件创建
@PostMapping
public String upload(MultipartFile file) {
String s=null;
try {
MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
//存入bucket不存在则创建,并设置为只读
if (!minioClient.bucketExists(BUCKETNAME)) {
minioClient.makeBucket(BUCKETNAME);
minioClient.setBucketPolicy(BUCKETNAME, "*.*", PolicyType.READ_ONLY);
}
String filename = file.getOriginalFilename();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 文件存储的目录结构
String objectName = sdf.format(new Date()) + "/" + filename;
// 存储文件
minioClient.putObject(BUCKETNAME, objectName, file.getInputStream(), file.getContentType());
LOGGER.info("文件上传成功!");
s=ENDPOINT + "/" + BUCKETNAME + "/" + objectName;
} catch (Exception e) {
LOGGER.info("上传发生错误: {}!", e.getMessage());
}
return s;
}
//文件删除
@DeleteMapping
public String delete(String name) {
try {
MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
minioClient.removeObject(BUCKETNAME, name);
} catch (Exception e) {
return "删除失败"+e.getMessage();
}
return "删除成功";
}
}
@GetMapping
public void downloadFiles(@RequestParam("filename") String filename, HttpServletResponse httpResponse) {
try {
MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
InputStream object = minioClient.getObject(BUCKETNAME, filename);
byte buf[] = new byte[1024];
int length = 0;
httpResponse.reset();
httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
httpResponse.setContentType("application/octet-stream");
httpResponse.setCharacterEncoding("utf-8");
OutputStream outputStream = httpResponse.getOutputStream();
while ((length = object.read(buf)) > 0) {
outputStream.write(buf, 0, length);
}
outputStream.close();
} catch (Exception ex) {
LOGGER.info("导出失败:", ex.getMessage());
}
}
编写好demo程序后使用postman进行测试:使用postman文件上传时选择body中的form-data选项,然后属性栏里面选择file属性就可以实现文件上传了。