From 300a0fb2b6e0a1255f40db1d618562dd52883e71 Mon Sep 17 00:00:00 2001
From: songhuangfeng123 <shf18767906695@163.com>
Date: 星期二, 26 七月 2022 18:57:30 +0800
Subject: [PATCH] 文件上传

---
 safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/service/FileService.java       |  155 +++++++++++++++++++
 /dev/null                                                                                         |  128 ----------------
 safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/utils/FileUtil.java            |  122 +++++++++++++++
 safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/controller/FileController.java |   31 +++
 safePlatfrom-out-web/pom.xml                                                                      |    4 
 5 files changed, 312 insertions(+), 128 deletions(-)

diff --git a/safePlatfrom-out-web/pom.xml b/safePlatfrom-out-web/pom.xml
index d609001..7055f3c 100644
--- a/safePlatfrom-out-web/pom.xml
+++ b/safePlatfrom-out-web/pom.xml
@@ -71,6 +71,10 @@
             <groupId>com.alibaba.cloud</groupId>
             <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+        </dependency>
 
 
     </dependencies>
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/controller/FileController.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/controller/FileController.java
new file mode 100644
index 0000000..629a787
--- /dev/null
+++ b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/controller/FileController.java
@@ -0,0 +1,31 @@
+package com.gkhy.safePlatform.minioDemo.controller;
+
+import com.gkhy.safePlatform.commons.vo.ResultVO;
+import com.gkhy.safePlatform.minioDemo.service.FileService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletResponse;
+
+
+@RestController
+@RequestMapping(value = "/file")
+public class FileController {
+
+    @Autowired
+    private FileService fileService;
+
+    @RequestMapping(value = "/upload",method = RequestMethod.POST)
+    public ResultVO uploadFile(@RequestParam MultipartFile file , @RequestParam Integer moduleType){
+        return fileService.uploadFile(file,moduleType);
+    }
+
+    @RequestMapping(value = "/download",method = RequestMethod.GET)
+    public void downloadFile(String fileName,HttpServletResponse response){
+        fileService.downloadFile(fileName,response);
+    }
+}
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/controller/MinioTest.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/controller/MinioTest.java
deleted file mode 100644
index a9edc3e..0000000
--- a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/controller/MinioTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.gkhy.safePlatform.minioDemo.controller;
-
-import com.gkhy.safePlatform.minioDemo.service.MinioAccessService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-
-@RestController
-@RequestMapping(value = "/test/file")
-public class MinioTest {
-
-    @Autowired
-    private MinioAccessService minioAccessService;
-
-    @RequestMapping(value = "/up",method = RequestMethod.GET)
-    private Object testFileUpload(){
-        return minioAccessService.uploadFile();
-    }
-
-    @RequestMapping(value = "/assume",method = RequestMethod.GET)
-    public Object testMinioSts(String obj){
-        return minioAccessService.getObjectUrl(obj);
-    }
-
-    @RequestMapping(value = "/put/presign",method = RequestMethod.GET)
-    public Object getPutObjectUrl(String obj){
-        return minioAccessService.getPutUrl(obj);
-    }
-}
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/service/FileService.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/service/FileService.java
new file mode 100644
index 0000000..dbaa30b
--- /dev/null
+++ b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/service/FileService.java
@@ -0,0 +1,155 @@
+package com.gkhy.safePlatform.minioDemo.service;
+
+import com.gkhy.safePlatform.commons.enums.ResultCodes;
+import com.gkhy.safePlatform.commons.vo.ResultVO;
+import com.gkhy.safePlatform.minioDemo.config.MinioConfig;
+import com.gkhy.safePlatform.minioDemo.enums.ModuleTypeEnums;
+import com.gkhy.safePlatform.minioDemo.utils.FileUtil;
+import io.minio.GetPresignedObjectUrlArgs;
+import io.minio.MinioClient;
+import io.minio.errors.*;
+import io.minio.http.Method;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+import static com.gkhy.safePlatform.minioDemo.enums.ModuleTypeEnums.*;
+
+@Service
+public class FileService {
+
+    @Resource
+    private MinioConfig minioConfig;
+
+    @Autowired
+    private MinioClient minioClient;
+
+    @Resource
+    private FileUtil fileUtil;
+
+    /**
+     * 文件下载
+     * @param fileName
+     * @param response
+     */
+    public void downloadFile(String fileName, HttpServletResponse response) {
+        fileUtil.downloadFile(fileName,response);
+    }
+
+    /**
+     * 文件上传
+     * @param file
+     * @param moduleType
+     * @return
+     */
+    public ResultVO<String> uploadFile(MultipartFile file, Integer moduleType) {
+        String url = "";
+        String moduleName = initModuleName(moduleType);
+
+        // 文件名转换
+        String time = new SimpleDateFormat("yyyyMMdd").format(new Date());
+        String fileSuffixName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".")+1);
+        String fileName = moduleName + "_" + time + "_" + initUUID()+"."+fileSuffixName;
+        try {
+            url=fileUtil.upload(file, fileName);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return new ResultVO<>(ResultCodes.OK, url);
+    }
+
+    /**
+     * 模块名称转换
+     */
+    private String initModuleName(Integer moduleType){
+        String moduleName = "";
+        ModuleTypeEnums moduleTypeEnums = ModuleTypeEnums.getReviewStatus(moduleType);
+        assert moduleTypeEnums != null;
+        switch (moduleTypeEnums) {
+            case EMERGENCY:
+                moduleName = EMERGENCY.getModuleName();
+                break;
+            case EQUIPMENT:
+                moduleName = EQUIPMENT.getModuleName();
+                break;
+            case GOAL_MANAGE:
+                moduleName = GOAL_MANAGE.getModuleName();
+                break;
+            case INCIDENT_MANAGE:
+                moduleName = INCIDENT_MANAGE.getModuleName();
+                break;
+            default:
+                break;
+        }
+        return moduleName;
+    }
+
+    /**
+     * 生成8位UUID
+     */
+    private String initUUID() {
+        String[] chars = new String[]{"a", "b", "c", "d", "e", "f",
+                "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
+                "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
+                "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
+                "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
+                "W", "X", "Y", "Z"};
+        StringBuffer shortBuffer = new StringBuffer();
+        String uuid = UUID.randomUUID().toString().replace("-", "");
+        for (int i = 0; i < 8; i++) {
+            String str = uuid.substring(i * 4, i * 4 + 4);
+            int x = Integer.parseInt(str, 16);
+            shortBuffer.append(chars[x % 0x3E]);
+        }
+        return shortBuffer.toString();
+    }
+
+
+
+
+
+    public String getPutUrl(String objName) {
+        String url = null;
+        try {
+            Map<String, String> reqParams = new HashMap<>();
+            reqParams.put("response-content-type", "application/json");
+            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
+                    .method(Method.PUT)
+                    .bucket(minioConfig.getBucketName())
+                    .object(objName)
+                    .expiry(60 * 2)
+                    .extraQueryParams(reqParams)
+                    .build());
+        } catch (ErrorResponseException e) {
+            e.printStackTrace();
+        } catch (InsufficientDataException e) {
+            e.printStackTrace();
+        } catch (InternalException e) {
+            e.printStackTrace();
+        } catch (InvalidKeyException e) {
+            e.printStackTrace();
+        } catch (InvalidResponseException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        } catch (XmlParserException e) {
+            e.printStackTrace();
+        } catch (ServerException e) {
+            e.printStackTrace();
+        }
+        return url;
+    }
+
+
+}
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/service/MinioAccessService.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/service/MinioAccessService.java
deleted file mode 100644
index 84b0682..0000000
--- a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/service/MinioAccessService.java
+++ /dev/null
@@ -1,128 +0,0 @@
-package com.gkhy.safePlatform.minioDemo.service;
-
-import com.gkhy.safePlatform.minioDemo.config.MinioConfig;
-import io.minio.BucketExistsArgs;
-import io.minio.GetPresignedObjectUrlArgs;
-import io.minio.MinioClient;
-import io.minio.UploadObjectArgs;
-import io.minio.errors.*;
-import io.minio.http.Method;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.Resource;
-import java.io.IOException;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.util.HashMap;
-import java.util.Map;
-
-@Service
-public class MinioAccessService {
-
-    @Resource
-    private MinioConfig minioConfig;
-
-    @Autowired
-    private MinioClient minioClient;
-
-    public Object uploadFile(){
-        try {
-            boolean bucketCheck =
-                    minioClient.bucketExists(BucketExistsArgs.builder()
-                            .bucket(minioConfig.getBucketName()).build());
-            if(bucketCheck == true){
-                minioClient.uploadObject(UploadObjectArgs.builder().bucket(minioConfig.getBucketName())
-                        .object("1.b3dm")
-                        .filename("G:\\b3dm\\b3dm60\\Tile_+000_+004\\Tile_+000_+004.b3dm")
-                        .build());
-                System.out.println("上传成功");
-            }
-        } catch (ServerException e) {
-            e.printStackTrace();
-        } catch (InsufficientDataException e) {
-            e.printStackTrace();
-        } catch (ErrorResponseException e) {
-            e.printStackTrace();
-        } catch (IOException e) {
-            e.printStackTrace();
-        } catch (NoSuchAlgorithmException e) {
-            e.printStackTrace();
-        } catch (InvalidKeyException e) {
-            e.printStackTrace();
-        } catch (InvalidResponseException e) {
-            e.printStackTrace();
-        } catch (XmlParserException e) {
-            e.printStackTrace();
-        } catch (InternalException e) {
-            e.printStackTrace();
-        }
-        return "1";
-    }
-
-    public String getObjectUrl(String objectName){
-        String url = null;
-        try {
-            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
-                    .method(Method.GET)
-                    .bucket(minioConfig.getBucketName())
-                    .object(objectName)
-                    .expiry(60).build());
-        } catch (ErrorResponseException e) {
-            e.printStackTrace();
-        } catch (InsufficientDataException e) {
-            e.printStackTrace();
-        } catch (InternalException e) {
-            e.printStackTrace();
-        } catch (InvalidKeyException e) {
-            e.printStackTrace();
-        } catch (InvalidResponseException e) {
-            e.printStackTrace();
-        } catch (IOException e) {
-            e.printStackTrace();
-        } catch (NoSuchAlgorithmException e) {
-            e.printStackTrace();
-        } catch (XmlParserException e) {
-            e.printStackTrace();
-        } catch (ServerException e) {
-            e.printStackTrace();
-        }
-        return url;
-    }
-
-    public String getPutUrl(String objName){
-        String url = null;
-        try {
-            Map<String, String> reqParams = new HashMap<>();
-            reqParams.put("response-content-type", "application/json");
-            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
-                    .method(Method.PUT)
-                    .bucket(minioConfig.getBucketName())
-                    .object(objName)
-                    .expiry(60*2)
-                    .extraQueryParams(reqParams)
-                    .build());
-        } catch (ErrorResponseException e) {
-            e.printStackTrace();
-        } catch (InsufficientDataException e) {
-            e.printStackTrace();
-        } catch (InternalException e) {
-            e.printStackTrace();
-        } catch (InvalidKeyException e) {
-            e.printStackTrace();
-        } catch (InvalidResponseException e) {
-            e.printStackTrace();
-        } catch (IOException e) {
-            e.printStackTrace();
-        } catch (NoSuchAlgorithmException e) {
-            e.printStackTrace();
-        } catch (XmlParserException e) {
-            e.printStackTrace();
-        } catch (ServerException e) {
-            e.printStackTrace();
-        }
-        return url;
-    }
-
-
-}
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/utils/FileUtil.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/utils/FileUtil.java
new file mode 100644
index 0000000..2036414
--- /dev/null
+++ b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/minioDemo/utils/FileUtil.java
@@ -0,0 +1,122 @@
+package com.gkhy.safePlatform.minioDemo.utils;
+
+import com.gkhy.safePlatform.minioDemo.config.MinioConfig;
+import com.sun.org.apache.regexp.internal.RE;
+import io.minio.*;
+import io.minio.MinioClient;
+import io.minio.errors.*;
+import io.minio.http.Method;
+import lombok.SneakyThrows;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+@Configuration
+public class FileUtil {
+
+    @Resource
+    private MinioConfig minioConfig;
+
+    @Autowired
+    private MinioClient minioClient;
+
+
+    /**
+     * 文件下载
+     * @param fileName
+     * @param response
+     */
+    public void downloadFile(String fileName, HttpServletResponse response) {
+        try {
+            InputStream file = minioClient.getObject(GetObjectArgs.builder()
+                    .bucket(minioConfig.getBucketName())
+                    .object(fileName)
+                    .build());
+            String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
+            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
+            ServletOutputStream servletOutputStream = response.getOutputStream();
+            int len;
+            byte[] buffer = new byte[1024];
+            while ((len = file.read(buffer)) > 0) {
+                servletOutputStream.write(buffer, 0, len);
+            }
+            servletOutputStream.flush();
+            file.close();
+            servletOutputStream.close();
+        } catch (ErrorResponseException e) {
+            e.printStackTrace();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    /**
+     * 文件上传
+     *
+     * @param file       文件
+     * @param fileName   存储的文件名称
+     */
+    public String upload(MultipartFile file, String fileName) {
+        String url;
+        try {
+            PutObjectArgs objectArgs = PutObjectArgs.builder()
+                    .bucket(minioConfig.getBucketName())
+                    .object(fileName)
+                    .stream(file.getInputStream(), file.getSize(), -1)
+                    .contentType(file.getContentType())
+                    .build();
+            //文件名称相同会覆盖
+            minioClient.putObject(objectArgs);
+            url = getFileUrl(fileName);
+        } catch (Exception e) {
+            e.printStackTrace();
+            url = "";
+        }
+        return url;
+    }
+
+    /**
+     * 文件访问路径
+     *
+     * @param objectName 存储桶里的对象名称
+     * expiry :链接失效时间,秒为单位
+     * @return
+     */
+    public String getFileUrl(String objectName) {
+        String url = null;
+        try {
+            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
+                    .method(Method.GET)
+                    .bucket(minioConfig.getBucketName())
+                    .object(objectName)
+                    .expiry(60).build());
+        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | XmlParserException | ServerException e) {
+            e.printStackTrace();
+        }
+        return url;
+    }
+
+
+    /**
+     * 检查存储桶是否存在
+     *
+     * @return
+     */
+    @SneakyThrows
+    public boolean bucketCheck() {
+        boolean flag = minioClient.bucketExists(BucketExistsArgs.builder()
+                .bucket(minioConfig.getBucketName()).build());
+        return flag;
+    }
+
+}

--
Gitblit v1.9.2