springboot整合minio实现⽂件上传与下载且⽀持链接永久访问
⽬录
1、minio部署
2、项⽬搭建
3、⽂件上传
4、⽂件下载
5、⽂件永久链接下载
1、minio部署
1.1 拉取镜像
docker pull minio/minio
1.2 创建数据⽬录
mkdir -p /home/guanz/minio
mkdir -p /home/guanz/minio/midata
1.3 启动minio
docker run -d -p 9000:9000 -p 9001:9001 --restart=always -e MINIO_ACCESS_KEY=guanz -e MINIO_SECRET_KEY=guanz@123 -v $PWD/midata:/data  minio/minio server /data --console-address "192.168.1.139:9001"
2、项⽬搭建
2.1 引⼊jar
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.0.3</version>
</dependency>
2.l
spring
minio:
# Minio服务器地址
endpoint: 192.168.1.139:9000
port: 9001
create-bucket: true
bucketName: push-test
# Minio服务器账号
accessKey: guanz
# Minio服务器密码
secretKey: guanz@123
secure: false
configDir: /home/push
# ⽂件⼤⼩单位M
maxFileSize: 10
expires: 604800
2.4 MinioConfig.java
package com.pavis.fig;
import io.minio.MinioClient;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.t.properties.ConfigurationProperties;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @program: push-saas
* @description:
* @author: Guanzi
* @created: 2021/11/02 13:47
*/
@Data
@Component
@ConfigurationProperties(prefix = "minio")
@Slf4j
@Configuration
public class MinioConfig {
@ApiModelProperty("endPoint是⼀个URL,域名,IPv4或者IPv6地址")
@Value("${dpoint}")
private String endpoint;
@ApiModelProperty("TCP/IP端⼝号")
@Value("${spring.minio.port}")
private int port;
@ApiModelProperty("accessKey类似于⽤户ID,⽤于唯⼀标识你的账户")
@Value("${spring.minio.accessKey}")
private String accessKey;
@ApiModelProperty("secretKey是你账户的密码")
@Value("${spring.minio.secretKey}")
private String secretKey;
@ApiModelProperty("如果是true,则⽤的是https⽽不是http,默认值是true")
@Value("${spring.minio.secure}")
private Boolean secure;
@ApiModelProperty("默认存储桶")
@Value("${spring.minio.bucketName}")
private String bucketName;
@ApiModelProperty("配置⽬录")
@Value("${figDir}")
private String configDir;
@ApiModelProperty("⽂件⼤⼩")
@Value("${spring.minio.maxFileSize}")
private Integer maxFileSize;
@ApiModelProperty("签名有效时间")
@Value("${pires}")
private Integer expires;
/**
* 注⼊minio 客户端
* @return
*/
@Bean
public MinioClient minioClient(){
log.info("endpoint:{},port:{},accessKey:{},secretKey:{},secure:{}",endpoint, port, accessKey, secretKey,secure);
return MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
}
}
3、⽂件上传
3.1 关键代码
MinioController.java
/**
* ⽂件上传
* @param file
* @return
*/
@PostMapping("/upload")
public Map<String, Object> upload(MultipartFile file){
return minioService.upload(file);
}
MinioServiceImpl.java
@Override
public Map<String, Object> upload(MultipartFile file) {
Map<String, Object> res = new HashMap<>();
try {
BucketExistsArgs bucketArgs = BucketExistsArgs.builder().bucket(bucketName).build();
/
/ todo 检查bucket是否存在。
boolean found = minioClient.bucketExists(bucketArgs);
PutObjectArgs objectArgs = PutObjectArgs.builder().OriginalFilename())
.bucket(bucketName)
.ContentType())
.InputStream(), Size(), -1).build();
ObjectWriteResponse objectWriteResponse = minioClient.putObject(objectArgs);
System.out.ag());
res.put("code", "1");
res.put("mess", "ok");
return res;
} catch (Exception e) {
e.printStackTrace();
log.Message());
}
res.put("code", "0");
return res;
}
4、⽂件下载
@Override
public void download(String filename, HttpServletResponse res) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorRe        B
ucketExistsArgs bucketArgs = BucketExistsArgs.builder().bucket(bucketName).build();
boolean bucketExists = minioClient.bucketExists(bucketArgs);
log.info("bucketExists:{}", bucketExists);
GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
.object(filename).build();
try (GetObjectResponse response = Object(objectArgs)) {
byte[] buf = new byte[1024];
int len;
try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
while ((len = ad(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
byte[] bytes = os.toByteArray();
res.setCharacterEncoding("utf-8");
res.setContentType("application/force-download");// 设置强制下载不打开
res.addHeader("Content-Disposition", "attachment;fileName=" + filename);
try (ServletOutputStream stream = OutputStream()) {
stream.write(bytes);
stream.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
下载地址:
5、⽂件永久链接下载
5.1 配置
5.2 关键代码
/**
* ⽣成⼀个GET请求的分享链接。
* 失效时间默认是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶⾥的对象名称
* @param expires    失效时间(以秒为单位),默认是7天,不得⼤于七天
* @return
*/
public String presignedGetObject(String bucketName, String objectName, Integer expires) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, Xm        BucketExistsArgs bucketArgs = BucketExistsArgs.builder().bucket(bucketName).build();
boolean bucketExists = minioClient.bucketExists(bucketArgs);
// boolean flag = bucketExists(bucketName);
String url = "";
if (bucketExists) {
try {
if (expires == null){
spring怎么读文件expires = 604800;
}
GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucketName)
.
object(objectName)
// .expiry(expires)
.build();
url = PresignedObjectUrl(getPresignedObjectUrlArgs);
log.info("*******url2:{}",url);
} catch (Exception e) {
log.info("presigned get object fail:{}",e);
}
}
return url;
}
⾄此,springboot+minio 结束。
到此这篇关于springboot整合minio实现⽂件上传与下载且⽀持链接永久访问的⽂章就介绍到这了,更多相关springboot minio ⽂件上传下载内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。