springboot整合minio實(shí)現(xiàn)文件上傳與下載且支持鏈接永久訪問
1、minio部署
1.1 拉取鏡像
docker pull minio/minio
1.2 創(chuàng)建數(shù)據(jù)目錄
mkdir -p /home/guanz/minio mkdir -p /home/guanz/minio/midata
1.3 啟動(dòng)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、項(xiàng)目搭建
2.1 引入jar
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.0.3</version>
</dependency>
2.2 application-dev.yml
spring
minio:
# Minio服務(wù)器地址
endpoint: http://192.168.1.139:9000
port: 9001
create-bucket: true
bucketName: push-test
# Minio服務(wù)器賬號(hào)
accessKey: guanz
# Minio服務(wù)器密碼
secretKey: guanz@123
secure: false
configDir: /home/push
# 文件大小 單位M
maxFileSize: 10
expires: 604800
2.4 MinioConfig.java
package com.pavis.app.saasbacken.config;
import io.minio.MinioClient;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.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是一個(gè)URL,域名,IPv4或者IPv6地址")
? ? @Value("${spring.minio.endpoint}")
? ? private String endpoint;
? ? @ApiModelProperty("TCP/IP端口號(hào)")
? ? @Value("${spring.minio.port}")
? ? private int port;
? ? @ApiModelProperty("accessKey類似于用戶ID,用于唯一標(biāo)識(shí)你的賬戶")
? ? @Value("${spring.minio.accessKey}")
? ? private String accessKey;
? ? @ApiModelProperty("secretKey是你賬戶的密碼")
? ? @Value("${spring.minio.secretKey}")
? ? private String secretKey;
? ? @ApiModelProperty("如果是true,則用的是https而不是http,默認(rèn)值是true")
? ? @Value("${spring.minio.secure}")
? ? private Boolean secure;
? ? @ApiModelProperty("默認(rèn)存儲(chǔ)桶")
? ? @Value("${spring.minio.bucketName}")
? ? private String bucketName;
? ? @ApiModelProperty("配置目錄")
? ? @Value("${spring.minio.configDir}")
? ? private String configDir;
? ? @ApiModelProperty("文件大小")
? ? @Value("${spring.minio.maxFileSize}")
? ? private Integer maxFileSize;
? ? @ApiModelProperty("簽名有效時(shí)間")
? ? @Value("${spring.minio.expires}")
? ? 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 關(guān)鍵代碼
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().object(file.getOriginalFilename())
? ? ? ? ? ? ? ? ? ? .bucket(bucketName)
? ? ? ? ? ? ? ? ? ? .contentType(file.getContentType())
? ? ? ? ? ? ? ? ? ? .stream(file.getInputStream(), file.getSize(), -1).build();
? ? ? ? ? ? ObjectWriteResponse objectWriteResponse = minioClient.putObject(objectArgs);
? ? ? ? ? ? System.out.println(objectWriteResponse.etag());
? ? ? ? ? ? res.put("code", "1");
? ? ? ? ? ? res.put("mess", "ok");
? ? ? ? ? ? return res;
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? log.info(e.getMessage());
? ? ? ? }
? ? ? ? res.put("code", "0");
? ? ? ? return res;
? ? }4、文件下載
@Override
? ? public void download(String filename, HttpServletResponse res) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
? ? ? ? BucketExistsArgs bucketArgs = BucketExistsArgs.builder().bucket(bucketName).build();
? ? ? ? boolean bucketExists = minioClient.bucketExists(bucketArgs);
? ? ? ? log.info("bucketExists:{}", bucketExists);
? ? ? ? GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
? ? ? ? ? ? ? ? .object(filename).build();
? ? ? ? System.err.println("objectArgs:" + JSON.toJSONString(objectArgs));
? ? ? ? try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
? ? ? ? ? ? System.err.println("response:" + JSON.toJSONString(response));
? ? ? ? ? ? byte[] buf = new byte[1024];
? ? ? ? ? ? int len;
? ? ? ? ? ? try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
? ? ? ? ? ? ? ? while ((len = response.read(buf)) != -1) {
? ? ? ? ? ? ? ? ? ? os.write(buf, 0, len);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? os.flush();
? ? ? ? ? ? ? ? byte[] bytes = os.toByteArray();
? ? ? ? ? ? ? ? res.setCharacterEncoding("utf-8");
? ? ? ? ? ? ? ? res.setContentType("application/force-download");// 設(shè)置強(qiáng)制下載不打開
? ? ? ? ? ? ? ? res.addHeader("Content-Disposition", "attachment;fileName=" + filename);
? ? ? ? ? ? ? ? try (ServletOutputStream stream = res.getOutputStream()) {
? ? ? ? ? ? ? ? ? ? stream.write(bytes);
? ? ? ? ? ? ? ? ? ? stream.flush();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
}下載地址:

5、文件永久鏈接下載
5.1 配置

5.2 關(guān)鍵代碼
/**
? ? * 生成一個(gè)GET請(qǐng)求的分享鏈接。
? ? * 失效時(shí)間默認(rèn)是7天。
? ? *
? ? * @param bucketName 存儲(chǔ)桶名稱
? ? * @param objectName 存儲(chǔ)桶里的對(duì)象名稱
? ? * @param expires ? ?失效時(shí)間(以秒為單位),默認(rèn)是7天,不得大于七天
? ? * @return
? ? */
? ?public String presignedGetObject(String bucketName, String objectName, Integer expires) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
? ? ? ?BucketExistsArgs bucketArgs = BucketExistsArgs.builder().bucket(bucketName).build();
? ? ? ?boolean bucketExists = minioClient.bucketExists(bucketArgs);
? ? ? ?// boolean flag = bucketExists(bucketName);
? ? ? ?String url = "";
? ? ? ?if (bucketExists) {
? ? ? ? ? ?try {
? ? ? ? ? ? ? ?if (expires == null){
? ? ? ? ? ? ? ? ? ?expires = 604800;
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
? ? ? ? ? ? ? ? ? ? ? ?.method(Method.GET)
? ? ? ? ? ? ? ? ? ? ? ?.bucket(bucketName)
? ? ? ? ? ? ? ? ? ? ? ?.object(objectName)
? ? ? ? ? ? ? ? ? ? ? ?// .expiry(expires)
? ? ? ? ? ? ? ? ? ? ? ?.build();
? ? ? ? ? ? ? ?url = minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
? ? ? ? ? ? ? ?log.info("*******url2:{}",url);
? ? ? ? ? ?} catch (Exception e) {
? ? ? ? ? ? ? ?log.info("presigned get object fail:{}",e);
? ? ? ? ? ?}
? ? ? ?}
? ? ? ?return url;
? ?}下載地址:http://192.168.1.139:9000/push-test/qiyeku.jpg
至此,springboot+minio 結(jié)束。
到此這篇關(guān)于springboot整合minio實(shí)現(xiàn)文件上傳與下載且支持鏈接永久訪問的文章就介紹到這了,更多相關(guān)springboot minio 文件上傳下載 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java開發(fā)分布式服務(wù)框架Dubbo服務(wù)引用過程詳解
這篇文章主要為大家介紹了java開發(fā)分布式服務(wù)框架Dubbo服務(wù)引用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
Java中ArrayIndexOutOfBoundsException 異常報(bào)錯(cuò)的解決方案
本文主要介紹了Java中ArrayIndexOutOfBoundsException 異常報(bào)錯(cuò)的解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
java數(shù)據(jù)結(jié)構(gòu)與算法之noDups去除重復(fù)項(xiàng)算法示例
這篇文章主要介紹了java數(shù)據(jù)結(jié)構(gòu)與算法之noDups去除重復(fù)項(xiàng)算法實(shí)現(xiàn)技巧,程序代碼非常簡(jiǎn)單,關(guān)鍵在于循環(huán)與判定,需要的朋友可以參考下2016-08-08

