Browse Source

fix 修改文件从oss下载的方式

DYH2020 2 years ago
parent
commit
3a1c282629

+ 50 - 8
src/main/java/com/ywt/mg/domain/models/OssSettring.java

@@ -4,15 +4,14 @@ import com.aliyun.oss.ClientException;
 import com.aliyun.oss.OSS;
 import com.aliyun.oss.OSSClientBuilder;
 import com.aliyun.oss.OSSException;
+import com.aliyun.oss.model.OSSObject;
 import com.aliyun.oss.model.PutObjectRequest;
 import com.ywt.mg.core.utils.Checker;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.OutputStream;
+import java.io.*;
 import java.util.Date;
 
 /**
@@ -101,11 +100,8 @@ public class OssSettring {
             logger.info("Error Code:" + oe.getErrorCode());
             logger.info("Request ID:" + oe.getRequestId());
             logger.info("Host ID:" + oe.getHostId());
-        } catch (ClientException ce) {
-            logger.info("Caught an ClientException, which means the client encountered "
-                    + "a serious internal problem while trying to communicate with OSS, "
-                    + "such as not being able to access the network.");
-            logger.info("Error Message:" + ce.getMessage());
+        } catch (Exception e) {
+            logger.info("Error Message:{}\t{}" + e.getMessage(), e);
         } finally {
             if (ossClient != null) {
                 ossClient.shutdown();
@@ -113,4 +109,50 @@ public class OssSettring {
         }
         return "";
     }
+
+    /**
+     * inputStream转byte数组
+     *
+     * @param inputStream 输入流对象
+     * @return byte数组
+     */
+    public static byte[] inputStreamToByteArray(InputStream inputStream) {
+        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
+            byte[] buffer = new byte[1024];
+            int num;
+            while ((num = inputStream.read(buffer)) != -1) {
+                byteArrayOutputStream.write(buffer, 0, num);
+            }
+            byteArrayOutputStream.flush();
+            return byteArrayOutputStream.toByteArray();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return new byte[]{};
+    }
+
+    public byte[] readFile(String url) {
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+        // 接收返回的url
+        try {
+            OSSObject ossObject = ossClient.getObject(fileBucketName, url);
+            logger.info("uploadFile:saveFileName:{},\turl:{}", fileBucketName, url);
+            return inputStreamToByteArray(ossObject.getObjectContent());
+        } catch (OSSException oe) {
+            logger.info("Caught an OSSException, which means your request made it to OSS, "
+                    + "but was rejected with an error response for some reason.");
+            logger.info("Error Message:" + oe.getErrorMessage());
+            logger.info("Error Code:" + oe.getErrorCode());
+            logger.info("Request ID:" + oe.getRequestId());
+            logger.info("Host ID:" + oe.getHostId());
+        } catch (Exception e) {
+            logger.info("Error Message:{}\t{}" + e.getMessage(), e);
+        } finally {
+            if (ossClient != null) {
+                ossClient.shutdown();
+            }
+        }
+        return null;
+    }
 }

+ 8 - 2
src/main/java/com/ywt/mg/web/common/FileSrv.java

@@ -93,9 +93,12 @@ public class FileSrv {
      *
      * @param filename 文件名
      * @param path     文件路径
-     * @param bytes    文件
+     * @param bio    文件
      * @return 文件路径
+     *
+     * 不采用这个方法,统一采用java的方法进行下载和上传文件,{@link OssSettring}
      */
+    @Deprecated
     public String uploadFile(String filename, String path,  ByteArrayInputStream bio) {
         try {
             UploadFileRequest rest = UploadFileRequest.newBuilder()
@@ -120,14 +123,17 @@ public class FileSrv {
      * @return
      */
     public byte[] readFile(String key) {
+        return ossSettring.readFile(key);
+        /*
+        // 文件太大,grpc之间传输会出错,node调节传输大小限制的方法暂时没找到,暂时采用java的方式进行传输
         ReadFileRequest req = ReadFileRequest.newBuilder().setFileUrl(key).build();
         ReadFileResponse res = fileServiceBlockingStub.readFile(req);
 
         if (res.getCode() == 0) {
             return res.getDatas().toByteArray();
         }
-
         return null;
+         */
     }
 
 }

+ 51 - 0
src/main/java/com/ywt/mg/web/controllers/TestController.java

@@ -4,6 +4,7 @@ import com.google.protobuf.ByteString;
 import com.ywt.gapi.base.file.FileServiceGrpc;
 import com.ywt.gapi.base.file.UploadFileRequest;
 import com.ywt.gapi.base.file.UploadFileResponse;
+import com.ywt.mg.configs.Constants;
 import com.ywt.mg.core.MGRight;
 import com.ywt.mg.core.utils.Checker;
 import com.ywt.mg.core.utils.FormatUtil;
@@ -19,6 +20,7 @@ import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
+import javax.servlet.http.HttpServletResponse;
 import java.io.*;
 import java.util.Date;
 
@@ -39,6 +41,9 @@ public class TestController {
     @Autowired
     private OssSettring ossSettring;
 
+    @Autowired
+    private FileSrv fileSrv;
+
     @RequestMapping({"/test"})
     public String test() {
         // 本地文件上传到oss,文件名带后缀
@@ -109,4 +114,50 @@ public class TestController {
         return url;
     }
 
+    @RequestMapping({"/download"})
+    public void download(HttpServletResponse httpServletResponse) throws Exception{
+        String fileName = "订餐订单列表.xls";
+        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), Constants.CHARSET_NAME));
+        httpServletResponse.setContentType("application/vnd.ms-excel;charset=UTF-8");
+        httpServletResponse.setHeader("Pragma", "no-cache");
+        httpServletResponse.setHeader("Cache-Control", "no-cache");
+        httpServletResponse.setDateHeader("Expires", 0);
+
+        OutputStream out = httpServletResponse.getOutputStream();
+        String url = Checker.getStringValue("big_data_file/excel/2022-11/订餐订单列表20221121230636.xls.xls");
+        if (!Checker.isNone(url)) {
+            byte[] b = fileSrv.readFile(url);
+            if (!Checker.isNone(b)) {
+                if (!Checker.isNone(b)) {
+                    out.write(b);
+                }
+            }
+            out.flush();
+            out.close();
+        }
+    }
+
+    @RequestMapping({"/download1"})
+    public void download1(HttpServletResponse httpServletResponse) throws Exception{
+        String fileName = "订餐订单列表.xls";
+        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), Constants.CHARSET_NAME));
+        httpServletResponse.setContentType("application/vnd.ms-excel;charset=UTF-8");
+        httpServletResponse.setHeader("Pragma", "no-cache");
+        httpServletResponse.setHeader("Cache-Control", "no-cache");
+        httpServletResponse.setDateHeader("Expires", 0);
+
+        OutputStream out = httpServletResponse.getOutputStream();
+        String url = Checker.getStringValue("big_data_file/excel/2022-11/订餐订单列表20221121230636.xls.xls");
+        if (!Checker.isNone(url)) {
+            byte[] b = ossSettring.readFile(url);
+            if (!Checker.isNone(b)) {
+                if (!Checker.isNone(b)) {
+                    out.write(b);
+                }
+            }
+            out.flush();
+            out.close();
+        }
+    }
+
 }