国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Java實(shí)現(xiàn)minio上傳、下載、刪除文件,支持https訪問

這篇具有很好參考價(jià)值的文章主要介紹了Java實(shí)現(xiàn)minio上傳、下載、刪除文件,支持https訪問。希望對大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

MinIO 是一款高性能、分布式的對象存儲系統(tǒng),Minio是基于Go語言編寫的對象存儲服務(wù),適合于存儲大容量非結(jié)構(gòu)化的數(shù)據(jù),例如圖片、音頻、視頻、備份數(shù)據(jù)等傳統(tǒng)對象存儲用例(例如輔助存儲,災(zāi)難恢復(fù)和歸檔)方面表現(xiàn)出色。

一、配置

導(dǎo)入minio依賴包

        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.0.3</version>
        </dependency>

application.yml配置文件

minio:
  #注意此處是https,由于后續(xù)討論協(xié)議問題因此提前修改,不需要的可自行修改為http
  endpoint: https://xxx.xxx.xx:9002 
  accesskey: minioadmin  #你的服務(wù)賬號
  secretkey: minioadmin  #你的服務(wù)密碼

配置MinioInfo文件

@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioInfo {

    private String endpoint;

    private String accesskey;

    private String secretkey;
}

配置MinioConfig文件

@Configuration
@EnableConfigurationProperties(MinioInfo.class)
public class MinioConfig {

    @Autowired
    private MinioInfo minioInfo;

    /**
     * 獲取 MinioClient
     */
    @Bean
    public MinioClient minioClient() throws NoSuchAlgorithmException, KeyManagementException {
        return MinioClient.builder().endpoint(minioInfo.getEndpoint())
                .credentials(minioInfo.getAccesskey(),minioInfo.getSecretkey())
                .build();
   }
}

二、上傳、下載、刪除文件

MinioUtils類

import io.minio.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author: MM
 * @date: 2023-03-09 10:09
 */
@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioInfo minioInfo;


    /**
     * 上傳文件
     * @param file
     * @param bucketName
     * @return
     * @throws Exception
     */
    public String uploadFile(MultipartFile file,String bucketName){
        if (null==file || 0 == file.getSize()){
            log.error("msg","上傳文件不能為空");
            return null;
        }
        try {
            //判斷是否存在
            createBucket(bucketName);
            //原文件名
            String originalFilename=file.getOriginalFilename();
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(originalFilename).stream(
                            file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            return minioInfo.getEndpoint()+"/"+bucketName+"/"+originalFilename;
        }catch (Exception e){
            log.error("上傳失?。簕}",e.getMessage());
        }
        log.error("msg","上傳失敗");
        return null;
    }

   /**
     * 通過字節(jié)流上傳
     * @param imageFullPath
     * @param bucketName
     * @param imageData
     * @return
     */
    public String uploadImage(String imageFullPath,
                              String bucketName,
                              byte[] imageData){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);
        try {
            //判斷是否存在
            createBucket(bucketName);
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(imageFullPath)
                    .stream(byteArrayInputStream,byteArrayInputStream.available(),-1)
                    .contentType(".jpg")
                    .build());
            return minioInfo.getEndpoint()+"/"+bucketName+"/"+imageFullPath;
        }catch (Exception e){
            log.error("上傳失?。簕}",e.getMessage());
        }
        log.error("msg","上傳失敗");
        return null;
    }

    /**
     * 刪除文件
     * @param bucketName
     * @param fileName
     * @return
     */
    public int removeFile(String bucketName,String fileName){
        try {
            //判斷桶是否存在
            boolean res=minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (res) {
                //刪除文件
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName)
                        .object(fileName).build());
            }
        } catch (Exception e) {
            System.out.println("刪除文件失敗");
            e.printStackTrace();
            return 1;
        }
        System.out.println("刪除文件成功");
        return 0;
    }

/**
     * 下載文件
     * @param fileName
     * @param bucketName
     * @param response
     */
    public void fileDownload(String fileName,
                             String bucketName,
                             HttpServletResponse response) {

        InputStream inputStream   = null;
        OutputStream outputStream = null;
        try {
            if (StringUtils.isBlank(fileName)) {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                String data = "文件下載失敗";
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
                return;
            }

            outputStream = response.getOutputStream();
            // 獲取文件對象
            inputStream =minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            byte buf[] = new byte[1024];
            int length = 0;
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            // 輸出文件
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            System.out.println("下載成功");
            inputStream.close();
        } catch (Throwable ex) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String data = "文件下載失敗";
            try {
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
            }catch (IOException e){
                e.printStackTrace();
            }
        } finally {
            try {
                outputStream.close();
                if (inputStream != null) {
                    inputStream.close();
                }}catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    @SneakyThrows
    public void createBucket(String bucketName) {
        //如果不存在就創(chuàng)建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }
}

接下來創(chuàng)建個(gè)Controller使用就行了

上傳

/**
     * 上傳文件
     * @param file
     * @return
     */
@PostMapping(value = "/v1/minio/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public JSONObject uploadByMinio(@RequestParam(name = "file")MultipartFile file) {
        JSONObject jso = new JSONObject();
        //返回存儲路徑
        String path = minioUtils.uploadFile(file, "musicearphone");
        jso.put("code", 2000);
        jso.put("data", path);
        return jso;
    }
Java實(shí)現(xiàn)minio上傳、下載、刪除文件,支持https訪問

下載

/**
     * 下載文件 根據(jù)文件名
     * @param fileName
     * @param response
     */
    @GetMapping("/v1/get/download")
    public void download(@RequestParam(name = "fileName") String fileName,
                         HttpServletResponse response){
        try {
            minioUtils.fileDownload(fileName,"musicearphone",response);
        }catch (Exception e){
            e.printStackTrace();

        }
    }
Java實(shí)現(xiàn)minio上傳、下載、刪除文件,支持https訪問

刪除

/**
     * 通過文件名刪除文件
     * @param fileName
     * @return
     */
@PostMapping("/v1/minio/delete")
    @ResponseBody
    public JSONObject deleteByName(String fileName){
        JSONObject jso = new JSONObject();
        int res = minioUtils.removeFile("musicearphone", fileName);
        if (res!=0){
            jso.put("code",5000);
            jso.put("msg","刪除失敗");
        }
        jso.put("code",2000);
        jso.put("msg","刪除成功");
        return jso;
    }
Java實(shí)現(xiàn)minio上傳、下載、刪除文件,支持https訪問

三、支持https訪問

由于公司項(xiàng)目的原因,項(xiàng)目訪問的方式是https,開始集成是minio服務(wù)器是http,在之前文章把minio開啟了https。

文章鏈接: https://blog.csdn.net/weixin_53799443/article/details/129335521

但在使用minio https服務(wù)的過程中發(fā)現(xiàn)文件上傳報(bào)錯(cuò)了

出現(xiàn)了以下的錯(cuò)誤

sun.security.validator.ValidatorException: 
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 
unable to find valid certification path to requested target

問題原因

源應(yīng)用程序不信任目標(biāo)應(yīng)用程序的證書,因?yàn)樵谠磻?yīng)用程序的JVM信任庫中找不到該證書或證書鏈(簡單來說minio服務(wù)不信任的證書問題導(dǎo)致)

解決辦法

通過java代碼取消ssl認(rèn)證,更新MinioConfig文件文章來源地址http://www.zghlxwxcb.cn/news/detail-445709.html

import io.minio.MinioClient;

import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * @author: MM
 * @date: 2023-03-09 10:05
 */
@Configuration
@EnableConfigurationProperties(MinioInfo.class)
public class MinioConfig {

    @Autowired
    private MinioInfo minioInfo;

    /**
     * 獲取 MinioClient
     * 取消ssl認(rèn)證
     */
    @Bean
    public MinioClient minioClient() throws NoSuchAlgorithmException, KeyManagementException {
//        return MinioClient.builder().endpoint(minioInfo.getEndpoint())
//                .credentials(minioInfo.getAccesskey(),minioInfo.getSecretkey())
//                .build();
        //取消ssl認(rèn)證
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
                    }
                    @Override
                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
                    }
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };

        X509TrustManager x509TrustManager = (X509TrustManager) trustAllCerts[0];
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory,x509TrustManager);

        builder.hostnameVerifier((s, sslSession) -> true);
        OkHttpClient okHttpClient = builder.build();

        return MinioClient.builder().endpoint(minioInfo.getEndpoint()).httpClient(okHttpClient).region("eu-west-1").credentials(minioInfo.getAccesskey()
                , minioInfo.getSecretkey()).build();
    }

}

到了這里,關(guān)于Java實(shí)現(xiàn)minio上傳、下載、刪除文件,支持https訪問的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包