ソースを参照

修改文件上传

Feick 4 年 前
コミット
6c26ba41d3

+ 9 - 0
src/main/java/com/yaoxiang/diagnosis/config/MinioProperties.java

@@ -6,6 +6,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
 public class MinioProperties {
 
     public static final String DEFAULT_BUCKET = "bucket";
+    private String prefix = "/file/download/";
 
     private String url;
     private String[] buckets = {};
@@ -23,6 +24,14 @@ public class MinioProperties {
         this.url = url;
     }
 
+    public String getPrefix() {
+        return prefix;
+    }
+
+    public void setPrefix(String prefix) {
+        this.prefix = prefix;
+    }
+
     public String[] getBuckets() {
         return buckets;
     }

+ 27 - 11
src/main/java/com/yaoxiang/diagnosis/controller/FileController.java

@@ -1,8 +1,9 @@
 package com.yaoxiang.diagnosis.controller;
 
 import com.yaoxiang.diagnosis.file.FileService;
+import com.yaoxiang.diagnosis.util.CommonUtil;
 import com.yaoxiang.diagnosis.util.OSSUtil;
-import com.yaoxiang.diagnosis.model.ResponseMessage;
+import com.yaoxiang.diagnosis.model.Reply;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
@@ -12,6 +13,7 @@ import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
 import java.io.IOException;
+import java.util.UUID;
 
 /**
  * @AUTHOR: DaiFengWen
@@ -28,36 +30,50 @@ public class FileController {
     private FileService fileService;
 
     @RequestMapping(value = "/img", method = RequestMethod.PUT)
-    public ResponseMessage uploadImg(@RequestParam MultipartFile file) {
+    public Reply uploadImg(@RequestParam MultipartFile file) {
         String file_name = null;
         try {
             int suffixIndex = file.getOriginalFilename().lastIndexOf(".");
             String suffix = file.getOriginalFilename().substring(suffixIndex);
             file_name = OSSUtil.INSTANCE.putFile(file.getInputStream(), suffix);
-            return ResponseMessage.getInstance(200, file_name);
+            return Reply.getInstance(200, file_name);
         } catch (IOException e) {
             e.printStackTrace();
         }
-        return ResponseMessage.getInstance(500, "error");
+        return Reply.getInstance(500, "error");
     }
 
     @ApiOperation(value = "上传文件")
     @PostMapping(value = "/upload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
-    public ResponseMessage uploadFile(@ApiParam(value = "文件") @RequestParam MultipartFile file) {
+    public Reply uploadFile(@RequestBody MultipartFile file) {
         try {
             int suffixIndex = file.getOriginalFilename().lastIndexOf(".");
             String suffix = file.getOriginalFilename().substring(suffixIndex);
-            return ResponseMessage.getInstance(200, OSSUtil.INSTANCE.putFile(file.getInputStream(), suffix));
+            String url = fileService.upload(file.getBytes(), CommonUtil.randomUUID() + suffix);
+            return Reply.ok(url);
         } catch (IOException e) {
             e.printStackTrace();
         }
-        return ResponseMessage.getInstance(500, "error");
+        return Reply.fail("error");
     }
 
-    @GetMapping("download/{path}/{filename}")
-    @ApiOperation("使用方式 curl localhost:8085/file/download/doc/xx.docx")
-    public ResponseEntity<byte[]> download(@PathVariable String path, @PathVariable String filename) throws Exception {
-        return fileService.download(path + "/" + filename);
+    //    @ApiOperation(value = "上传文件")
+//    @PostMapping(value = "/upload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
+//    public Reply uploadFile(@ApiParam(value = "文件") @RequestParam MultipartFile file) {
+//        try {
+//            int suffixIndex = file.getOriginalFilename().lastIndexOf(".");
+//            String suffix = file.getOriginalFilename().substring(suffixIndex);
+//            return Reply.getInstance(200, OSSUtil.INSTANCE.putFile(file.getInputStream(), suffix));
+//        } catch (IOException e) {
+//            e.printStackTrace();
+//        }
+//        return Reply.getInstance(500, "error");
+//    }
+
+    @GetMapping("/download/{bucketName}/{filename}")
+    @ApiOperation("使用方式 curl localhost:8085/file/download/prod/xx.docx")
+    public ResponseEntity<byte[]> download(@PathVariable String bucketName, @PathVariable String filename) throws IOException {
+        return fileService.download("/" + bucketName + "/" + filename);
     }
 
 }

+ 1 - 1
src/main/java/com/yaoxiang/diagnosis/file/AliyunFileService.java

@@ -56,7 +56,7 @@ public class AliyunFileService implements FileService {
     }
 
     @Override
-    public ResponseEntity<byte[]> download(String url) {
+    public ResponseEntity<byte[]> download(String url) throws IOException {
         return null;
     }
 }

+ 3 - 1
src/main/java/com/yaoxiang/diagnosis/file/FileService.java

@@ -2,8 +2,10 @@ package com.yaoxiang.diagnosis.file;
 
 import org.springframework.http.ResponseEntity;
 
+import java.io.IOException;
+
 public interface FileService {
     String upload(byte[] data, String filename);
 
-    ResponseEntity<byte[]> download(String url);
+    ResponseEntity<byte[]> download(String url) throws IOException;
 }

+ 1 - 1
src/main/java/com/yaoxiang/diagnosis/file/LocalFileService.java

@@ -64,7 +64,7 @@ public class LocalFileService implements FileService{
         return result;
     }
 
-    public ResponseEntity<byte[]> download(String filename){
+    public ResponseEntity<byte[]> download(String filename) throws IOException {
         byte[] body = download(properties.getUploadLocation(), filename);
         HttpHeaders headers = new HttpHeaders();
         headers.add("Cache-Control", "no-cache, no-store, must-revalidate");

+ 30 - 18
src/main/java/com/yaoxiang/diagnosis/file/MinioFileService.java

@@ -5,11 +5,19 @@ import com.yaoxiang.diagnosis.config.MinioProperties;
 import io.minio.MinioClient;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
 import org.springframework.util.Assert;
+import org.springframework.util.FileCopyUtils;
 
 import javax.annotation.Resource;
 import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URLEncoder;
 
 public class MinioFileService implements FileService {
 
@@ -20,17 +28,6 @@ public class MinioFileService implements FileService {
     @Resource
     private MinioClient minioClient;
 
-    public String upload(String filename) {
-        return "";
-//        return upload(filename, MinioProperties.DEFAULT_BUCKET);
-    }
-
-    private String upload(String filename, String bucket) throws Exception {
-        checkAndMake(bucket);
-//        minioClient.putObject(bucket,filename,);
-        return "";
-    }
-
     private void checkAndMake(String bucket) throws Exception {
         Assert.hasText(bucket, "bucket is blank");
         if (!minioClient.bucketExists(bucket)) {
@@ -78,15 +75,30 @@ public class MinioFileService implements FileService {
         return url;
     }
 
-//    private String buildUrl(String bucket, String filename) throws Exception {
-//        return minioClient.getObjectUrl(bucket, filename);
-//    }
-
     private String buildUrl(String bucket, String filename) {
-        return properties.getUrl() + bucket + "/" + filename;
+        return properties.getPrefix() + bucket + "/" + filename;
+    }
+
+    public ResponseEntity<byte[]> download(String url) throws IOException {
+        int index = url.lastIndexOf('/') + 1;
+        String uuidName = url.substring(index);
+        byte[] bytes = this.getFile(properties.getDefaultBucket(), uuidName);
+        HttpHeaders httpHeaders = new HttpHeaders();
+        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
+        httpHeaders.setContentLength(bytes.length);
+        httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(uuidName, "UTF-8"));
+        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
     }
 
-    public ResponseEntity<byte[]> download(String url) {
-        return null;
+    private byte[] getFile(String bucketName, String fileName) {
+        try {
+            final InputStream inputStream = minioClient.getObject(bucketName, fileName);
+            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            FileCopyUtils.copy(inputStream, bos);
+            return bos.toByteArray();
+        } catch (Exception e) {
+            logger.error("get object error,path=" + bucketName + ",filename=" + fileName, e);
+        }
+        return new byte[0];
     }
 }

+ 2 - 1
src/main/java/com/yaoxiang/diagnosis/file/NginxFileService.java

@@ -14,6 +14,7 @@ import org.springframework.util.MultiValueMap;
 import org.springframework.web.client.RestTemplate;
 
 import javax.annotation.PostConstruct;
+import java.io.IOException;
 
 public class NginxFileService implements FileService{
 
@@ -50,7 +51,7 @@ public class NginxFileService implements FileService{
     }
 
     @Override
-    public ResponseEntity<byte[]> download(String url) {
+    public ResponseEntity<byte[]> download(String url) throws IOException {
         return null;
     }
 

+ 12 - 5
src/main/java/com/yaoxiang/diagnosis/model/ResponseMessage.java → src/main/java/com/yaoxiang/diagnosis/model/Reply.java

@@ -5,24 +5,31 @@ package com.yaoxiang.diagnosis.model;
  * @DATE: Create in 2018/5/10 14:15
  * @DESCRIPTION:
  */
-public class ResponseMessage {
+public class Reply {
     private final String message;
     private final int code;
 
-    private ResponseMessage(int code, String message) {
+    private Reply(int code, String message) {
         this.message = message;
         this.code = code;
     }
 
-    public static ResponseMessage getInstance(int code, String message) {
-        return new ResponseMessage(code, message);
+    public static Reply ok(String message) {
+        return new Reply(200, message);
+    }
+
+    public static Reply fail(String message) {
+        return new Reply(500, message);
+    }
+
+    public static Reply getInstance(int code, String message) {
+        return new Reply(code, message);
     }
 
     public String getMessage() {
         return message;
     }
 
-
     public int getCode() {
         return code;
     }

+ 1 - 1
src/main/resources/application-cloud.properties

@@ -11,7 +11,7 @@ spring.redis.host=redis-master
 spring.redis.port=6379
 
 #外部要使用,所以不能为内部地址
-minio.url=https://minio.yaoxiangedu.com/
+minio.url=http://minio.yaoxiangedu.com/
 minio.secure=true
 minio.buckets=prod
 minio.defaultBucket=prod

+ 13 - 1
src/test/java/com/yaoxiang/diagnosis/service/NumberTest.java

@@ -1,11 +1,15 @@
 package com.yaoxiang.diagnosis.service;
 
+import com.yaoxiang.diagnosis.util.MD5Util;
 import org.junit.Test;
+import org.springframework.util.DigestUtils;
+
+import java.nio.charset.StandardCharsets;
 
 public class NumberTest {
 
     @Test
-    public void convert(){
+    public void convert() {
         int c = 81;
         int size = 99;
 //        NumberUtil.formatDouble()
@@ -13,4 +17,12 @@ public class NumberTest {
         System.out.println(c * 100.0 / size);
 
     }
+
+    @Test
+    public void test() {
+//        MD5Util.INSTANCE.md5("a123456");
+        String value = "a123456";
+        byte[] bytes = DigestUtils.md5Digest(value.getBytes(StandardCharsets.UTF_8));
+        System.out.println(new String(bytes, StandardCharsets.UTF_8));
+    }
 }