当前位置:   article > 正文

Java实现minio上传、下载、删除文件,支持https访问_minio下载文件

minio下载文件

MinIO 是一款高性能、分布式的对象存储系统,Minio是基于Go语言编写的对象存储服务,适合于存储大容量非结构化的数据,例如图片、音频、视频、备份数据等传统对象存储用例(例如辅助存储,灾难恢复和归档)方面表现出色。

一、配置

导入minio依赖包

  1. <dependency>
  2. <groupId>io.minio</groupId>
  3. <artifactId>minio</artifactId>
  4. <version>8.0.3</version>
  5. </dependency>

application.yml配置文件

  1. minio:
  2. #注意此处是https,由于后续讨论协议问题因此提前修改,不需要的可自行修改为http
  3. endpoint: https://xxx.xxx.xx:9002
  4. accesskey: minioadmin #你的服务账号
  5. secretkey: minioadmin #你的服务密码

配置MinioInfo文件

  1. @Data
  2. @Component
  3. @ConfigurationProperties(prefix = "minio")
  4. public class MinioInfo {
  5. private String endpoint;
  6. private String accesskey;
  7. private String secretkey;
  8. }

配置MinioConfig文件

  1. @Configuration
  2. @EnableConfigurationProperties(MinioInfo.class)
  3. public class MinioConfig {
  4. @Autowired
  5. private MinioInfo minioInfo;
  6. /**
  7. * 获取 MinioClient
  8. */
  9. @Bean
  10. public MinioClient minioClient() throws NoSuchAlgorithmException, KeyManagementException {
  11. return MinioClient.builder().endpoint(minioInfo.getEndpoint())
  12. .credentials(minioInfo.getAccesskey(),minioInfo.getSecretkey())
  13. .build();
  14. }
  15. }

二、上传、下载、删除文件

MinioUtils类

  1. import io.minio.*;
  2. import lombok.SneakyThrows;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.commons.lang.StringUtils;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Component;
  7. import org.springframework.web.multipart.MultipartFile;
  8. import javax.servlet.http.HttpServletResponse;
  9. import java.io.*;
  10. import java.net.URLEncoder;
  11. /**
  12. * @author: MM
  13. * @date: 2023-03-09 10:09
  14. */
  15. @Slf4j
  16. @Component
  17. public class MinioUtils {
  18. @Autowired
  19. private MinioClient minioClient;
  20. @Autowired
  21. private MinioInfo minioInfo;
  22. /**
  23. * 上传文件
  24. * @param file
  25. * @param bucketName
  26. * @return
  27. * @throws Exception
  28. */
  29. public String uploadFile(MultipartFile file,String bucketName){
  30. if (null==file || 0 == file.getSize()){
  31. log.error("msg","上传文件不能为空");
  32. return null;
  33. }
  34. try {
  35. //判断是否存在
  36. createBucket(bucketName);
  37. //原文件名
  38. String originalFilename=file.getOriginalFilename();
  39. minioClient.putObject(
  40. PutObjectArgs.builder().bucket(bucketName).object(originalFilename).stream(
  41. file.getInputStream(), file.getSize(), -1)
  42. .contentType(file.getContentType())
  43. .build());
  44. return minioInfo.getEndpoint()+"/"+bucketName+"/"+originalFilename;
  45. }catch (Exception e){
  46. log.error("上传失败:{}",e.getMessage());
  47. }
  48. log.error("msg","上传失败");
  49. return null;
  50. }
  51. /**
  52. * 通过字节流上传
  53. * @param imageFullPath
  54. * @param bucketName
  55. * @param imageData
  56. * @return
  57. */
  58. public String uploadImage(String imageFullPath,
  59. String bucketName,
  60. byte[] imageData){
  61. ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);
  62. try {
  63. //判断是否存在
  64. createBucket(bucketName);
  65. minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(imageFullPath)
  66. .stream(byteArrayInputStream,byteArrayInputStream.available(),-1)
  67. .contentType(".jpg")
  68. .build());
  69. return minioInfo.getEndpoint()+"/"+bucketName+"/"+imageFullPath;
  70. }catch (Exception e){
  71. log.error("上传失败:{}",e.getMessage());
  72. }
  73. log.error("msg","上传失败");
  74. return null;
  75. }
  76. /**
  77. * 删除文件
  78. * @param bucketName
  79. * @param fileName
  80. * @return
  81. */
  82. public int removeFile(String bucketName,String fileName){
  83. try {
  84. //判断桶是否存在
  85. boolean res=minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
  86. if (res) {
  87. //删除文件
  88. minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName)
  89. .object(fileName).build());
  90. }
  91. } catch (Exception e) {
  92. System.out.println("删除文件失败");
  93. e.printStackTrace();
  94. return 1;
  95. }
  96. System.out.println("删除文件成功");
  97. return 0;
  98. }
  99. /**
  100. * 下载文件
  101. * @param fileName
  102. * @param bucketName
  103. * @param response
  104. */
  105. public void fileDownload(String fileName,
  106. String bucketName,
  107. HttpServletResponse response) {
  108. InputStream inputStream = null;
  109. OutputStream outputStream = null;
  110. try {
  111. if (StringUtils.isBlank(fileName)) {
  112. response.setHeader("Content-type", "text/html;charset=UTF-8");
  113. String data = "文件下载失败";
  114. OutputStream ps = response.getOutputStream();
  115. ps.write(data.getBytes("UTF-8"));
  116. return;
  117. }
  118. outputStream = response.getOutputStream();
  119. // 获取文件对象
  120. inputStream =minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
  121. byte buf[] = new byte[1024];
  122. int length = 0;
  123. response.reset();
  124. response.setHeader("Content-Disposition", "attachment;filename=" +
  125. URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
  126. response.setContentType("application/octet-stream");
  127. response.setCharacterEncoding("UTF-8");
  128. // 输出文件
  129. while ((length = inputStream.read(buf)) > 0) {
  130. outputStream.write(buf, 0, length);
  131. }
  132. System.out.println("下载成功");
  133. inputStream.close();
  134. } catch (Throwable ex) {
  135. response.setHeader("Content-type", "text/html;charset=UTF-8");
  136. String data = "文件下载失败";
  137. try {
  138. OutputStream ps = response.getOutputStream();
  139. ps.write(data.getBytes("UTF-8"));
  140. }catch (IOException e){
  141. e.printStackTrace();
  142. }
  143. } finally {
  144. try {
  145. outputStream.close();
  146. if (inputStream != null) {
  147. inputStream.close();
  148. }}catch (IOException e){
  149. e.printStackTrace();
  150. }
  151. }
  152. }
  153. @SneakyThrows
  154. public void createBucket(String bucketName) {
  155. //如果不存在就创建
  156. if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
  157. minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
  158. }
  159. }
  160. }

接下来创建个Controller使用就行了

上传

  1. /**
  2. * 上传文件
  3. * @param file
  4. * @return
  5. */
  6. @PostMapping(value = "/v1/minio/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  7. @ResponseBody
  8. public JSONObject uploadByMinio(@RequestParam(name = "file")MultipartFile file) {
  9. JSONObject jso = new JSONObject();
  10. //返回存储路径
  11. String path = minioUtils.uploadFile(file, "musicearphone");
  12. jso.put("code", 2000);
  13. jso.put("data", path);
  14. return jso;
  15. }

下载

  1. /**
  2. * 下载文件 根据文件名
  3. * @param fileName
  4. * @param response
  5. */
  6. @GetMapping("/v1/get/download")
  7. public void download(@RequestParam(name = "fileName") String fileName,
  8. HttpServletResponse response){
  9. try {
  10. minioUtils.fileDownload(fileName,"musicearphone",response);
  11. }catch (Exception e){
  12. e.printStackTrace();
  13. }
  14. }

删除

  1. /**
  2. * 通过文件名删除文件
  3. * @param fileName
  4. * @return
  5. */
  6. @PostMapping("/v1/minio/delete")
  7. @ResponseBody
  8. public JSONObject deleteByName(String fileName){
  9. JSONObject jso = new JSONObject();
  10. int res = minioUtils.removeFile("musicearphone", fileName);
  11. if (res!=0){
  12. jso.put("code",5000);
  13. jso.put("msg","删除失败");
  14. }
  15. jso.put("code",2000);
  16. jso.put("msg","删除成功");
  17. return jso;
  18. }

三、支持https访问

由于公司项目的原因,项目访问的方式是https,开始集成是minio服务器是http,在之前文章把minio开启了https。

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

但在使用minio https服务的过程中发现文件上传报错了

出现了以下的错误

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

问题原因

源应用程序不信任目标应用程序的证书,因为在源应用程序的JVM信任库中找不到该证书或证书链(简单来说minio服务不信任的证书问题导致)

解决办法

通过java代码取消ssl认证,更新MinioConfig文件

  1. import io.minio.MinioClient;
  2. import okhttp3.OkHttpClient;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import javax.net.ssl.*;
  8. import java.security.KeyManagementException;
  9. import java.security.NoSuchAlgorithmException;
  10. import java.security.SecureRandom;
  11. import java.security.cert.X509Certificate;
  12. /**
  13. * @author: MM
  14. * @date: 2023-03-09 10:05
  15. */
  16. @Configuration
  17. @EnableConfigurationProperties(MinioInfo.class)
  18. public class MinioConfig {
  19. @Autowired
  20. private MinioInfo minioInfo;
  21. /**
  22. * 获取 MinioClient
  23. * 取消ssl认证
  24. */
  25. @Bean
  26. public MinioClient minioClient() throws NoSuchAlgorithmException, KeyManagementException {
  27. // return MinioClient.builder().endpoint(minioInfo.getEndpoint())
  28. // .credentials(minioInfo.getAccesskey(),minioInfo.getSecretkey())
  29. // .build();
  30. //取消ssl认证
  31. final TrustManager[] trustAllCerts = new TrustManager[]{
  32. new X509TrustManager() {
  33. @Override
  34. public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
  35. }
  36. @Override
  37. public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
  38. }
  39. @Override
  40. public X509Certificate[] getAcceptedIssuers() {
  41. return new X509Certificate[]{};
  42. }
  43. }
  44. };
  45. X509TrustManager x509TrustManager = (X509TrustManager) trustAllCerts[0];
  46. final SSLContext sslContext = SSLContext.getInstance("SSL");
  47. sslContext.init(null, trustAllCerts, new SecureRandom());
  48. final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
  49. OkHttpClient.Builder builder = new OkHttpClient.Builder();
  50. builder.sslSocketFactory(sslSocketFactory,x509TrustManager);
  51. builder.hostnameVerifier((s, sslSession) -> true);
  52. OkHttpClient okHttpClient = builder.build();
  53. return MinioClient.builder().endpoint(minioInfo.getEndpoint()).httpClient(okHttpClient).region("eu-west-1").credentials(minioInfo.getAccesskey()
  54. , minioInfo.getSecretkey()).build();
  55. }
  56. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/202636
推荐阅读
相关标签
  

闽ICP备14008679号