minio实现文件上传下载和删除功能
minio的中文文档:https://docs.min.io/cn/
minio安装
-
首先查询docker镜像:
docker search minio -
选着stars最高的那个拉取:
docker pull minio/minio -
启动minio服务器,并设置端口号,容器名,账号和密码:
docker run -p 9000:9000 --name minio -e MINIO_ACCESS_KEY=tanchuntcc -e MINIO_SECRET_KEY=tanchuntcc -v /data:/data minio/minio server /data
minio操作
-
启动成功后,访问你minio的ip地址,这里我docker安装在本机,所以是http://localhost:9000,输入刚刚设置的账号密码。
-
登陆后右下角可以创建bucket.
-
创建多个bucket后
-
可以选择编辑和删除
-
可以点击右下角上传文件
-
支持各种类型的文件:
首先创建一个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属性就可以实现文件上传了。
删除文件时输入文件的相对路径即可删除:
导出文件时填好文件名称,选择save and download即可在postman中导出文件:
示例
==============================================================================
<!-- minio工具类-->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>3.0.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.22</version>
<scope>compile</scope>
</dependency>
==============================================================================
InputStream inputStream = new FileInputStream(files.get(i));
MultipartFile multipartFile = new MockMultipartFile(files.get(i).getName(), files.get(i).getName(), ContentType.IMAGE_BMP.toString(), inputStream);
String path = MinioUtil.upload(multipartFile, infoResult.getString("specimenId"), i);
inputStream.close();
===============================================================================
package com.kanghua.manager.common.util;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
@Slf4j
public class MinioUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(MinioUtil.class);
private static String ENDPOINT;
private static String BUCKETNAME;
private static String ACCESSKEY;
private static String SECRETKEY;
@Value("${minio.endpoint}")
public void setENDPOINT(String ENDPOINT) {
MinioUtil.ENDPOINT = ENDPOINT;
}
@Value("${minio.bucketName}")
public void setBUCKETNAME(String BUCKETNAME) {
MinioUtil.BUCKETNAME = BUCKETNAME;
}
@Value("${minio.accessKey}")
public void setACCESSKEY(String ACCESSKEY) {
MinioUtil.ACCESSKEY = ACCESSKEY;
}
@Value("${minio.secretKey}")
public void setSECRETKEY(String SECRETKEY) {
MinioUtil.SECRETKEY = SECRETKEY;
}
public static MinioClient minioClient;
/**
* 初始化minio配置
*/
@PostConstruct
public void init() {
try {
log.info("Minio Initialize........................");
minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
//createBucket(BUCKETNAME);
log.info("Minio Initialize........................successful");
} catch (Exception e) {
e.printStackTrace();
log.error("初始化minio配置异常: 【{}】", e.fillInStackTrace());
}
}
/**
* 文件创建
*/
@PostMapping
public static String upload(MultipartFile file, String specimenId, int i) {
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 = specimenId + "_" + (i + 1 + "") + file.getName().substring(file.getName().lastIndexOf("."));
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;
LOGGER.info("文件上传地址:" + 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());
}
}
}
本文作者:韩憨
本文链接:https://www.cnblogs.com/hanby/p/14297199.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步