springboot整合minio,實現(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 啟動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.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ù)器賬號
    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是一個URL,域名,IPv4或者IPv6地址")
    @Value("${spring.minio.endpoint}")
    private String endpoint;

    @ApiModelProperty("TCP/IP端口號")
    @Value("${spring.minio.port}")
    private int port;

    @ApiModelProperty("accessKey類似于用戶ID,用于唯一標(biāo)識你的賬戶")
    @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)存儲桶")
    @Value("${spring.minio.bucketName}")
    private String bucketName;

    @ApiModelProperty("配置目錄")
    @Value("${spring.minio.configDir}")
    private String configDir;

    @ApiModelProperty("文件大小")
    @Value("${spring.minio.maxFileSize}")
    private Integer maxFileSize;

    @ApiModelProperty("簽名有效時間")
    @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è)置強制下載不打開
                res.addHeader("Content-Disposition", "attachment;fileName=" + filename);
                try (ServletOutputStream stream = res.getOutputStream()) {
                    stream.write(bytes);
                    stream.flush();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
}
下載地址:
image.png

5、文件永久鏈接下載

5.1 配置

image.png

5.2 關(guān)鍵代碼

/**
    * 生成一個GET請求的分享鏈接。
    * 失效時間默認(rèn)是7天。
    *
    * @param bucketName 存儲桶名稱
    * @param objectName 存儲桶里的對象名稱
    * @param expires    失效時間(以秒為單位),默認(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é)束。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容