Explorar el Código

fix 新增该项目上传OSS方法

DYH2020 hace 2 años
padre
commit
1bfb0ed0e1

BIN
download_file/订餐订单列表.xls


+ 6 - 0
pom.xml

@@ -188,6 +188,12 @@
             <artifactId>mysql-binlog-connector-java</artifactId>
             <version>0.13.0</version>
         </dependency>
+
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>3.10.2</version>
+        </dependency>
     </dependencies>
     <profiles>
         <profile>

+ 6 - 1
src/main/java/com/ywt/mg/configs/GrpcChannelBeans.java

@@ -8,13 +8,18 @@ import org.springframework.stereotype.Component;
 
 @Component
 public class GrpcChannelBeans {
+
+    private final int maxInboundMessageSize = 1024*1024*256;
+
     @Value("${service.agent.grpc.addr}")
     private String agentAddr;
 
     @Bean(name = "agentChannel")
     public Channel getAgentChannel() {
         String[] hostAndPort = agentAddr.split(":");
-        return ManagedChannelBuilder.forAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1])).usePlaintext(true).build();
+        return ManagedChannelBuilder.forAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1])).usePlaintext(true)
+                .maxInboundMessageSize(maxInboundMessageSize).build();
+//        return ManagedChannelBuilder.forAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1])).usePlaintext(true).build();
     }
 
 

+ 77 - 0
src/main/java/com/ywt/mg/domain/models/OssSettring.java

@@ -0,0 +1,77 @@
+package com.ywt.mg.domain.models;
+
+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.PutObjectRequest;
+import com.ywt.mg.core.utils.Checker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.io.File;
+import java.util.Date;
+
+/**
+ * @author daiyihua
+ * @create 2018-07-27 上午10:26
+ * @desc OSS直传参数设置
+ **/
+@Component
+public class OssSettring {
+
+    private static Logger logger = LoggerFactory.getLogger(OssSettring.class);
+
+    // Endpoint外网访问域名
+    public static final String endpoint = "oss-cn-shenzhen.aliyuncs.com";
+
+    // 用户请求的accessid
+    public static final String accessKeyId = "LTAI6J2CnMZpFOMA"; // 6MKOqxGiGU4AUk44
+
+    public static final String accessKeySecret = "S5imKc18OwO82527mZtSoUqr3De06f";    //ufu7nS8kS59awNihtjSonMETLI0KLy
+
+    public static final String fileBucketName = "ywt-files";
+
+    public String uploadFile(String localPath, String saveFileName){
+        // 创建OSSClient实例。
+        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
+
+        // 接收返回的url
+        String url = "";
+        try {
+            File file = new File(localPath);
+            if (Checker.isNone(file)) {
+                return "文件不存在";
+            }
+
+            // 创建PutObjectRequest对象。
+            PutObjectRequest putObjectRequest = new PutObjectRequest(fileBucketName, saveFileName, file);
+            // 上传文件
+            ossClient.putObject(putObjectRequest);
+            // 获取文件url
+            // url过期时间
+            Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7);
+            url = ossClient.generatePresignedUrl(fileBucketName, saveFileName, date).toString();
+            return url;
+        } 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 (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());
+        } finally {
+            if (ossClient != null) {
+                ossClient.shutdown();
+            }
+        }
+        return "";
+    }
+
+}

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

@@ -0,0 +1,112 @@
+package com.ywt.mg.web.controllers;
+
+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.core.MGRight;
+import com.ywt.mg.core.utils.Checker;
+import com.ywt.mg.core.utils.FormatUtil;
+import com.ywt.mg.domain.models.ConstantDef;
+import com.ywt.mg.domain.models.OssSettring;
+import com.ywt.mg.domain.models.enums.DownloadRecordStatusEnum;
+import com.ywt.mg.params.registeredOrder.RegisteredOrderListRequest;
+import com.ywt.mg.web.BaseResponse;
+import com.ywt.mg.web.DataResponse;
+import com.ywt.mg.web.common.FileSrv;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.io.*;
+import java.util.Date;
+
+/**
+ * @author daiyihua
+ * @create 2022-11-21 14:37
+ * @program download_service
+ * @description test
+ **/
+@MGRight(need = false)
+@RestController("/test")
+@RequestMapping({"/test"})
+public class TestController {
+
+    @Autowired
+    private FileServiceGrpc.FileServiceBlockingStub fileServiceBlockingStub;
+
+    @Autowired
+    private OssSettring ossSettring;
+
+    @RequestMapping({"/test"})
+    public String test() {
+        // 本地文件上传到oss,文件名带后缀
+        String fileName = "订餐订单列表";
+        // 前缀(路径)
+        String preLocalPath = ConstantDef.LOCAL_DOWNLOAD_FILE_PATH;
+        // 后缀(下载时间和格式)
+        String suffixFormat = FormatUtil.formatDate(new Date(), FormatUtil.FORMAT_DATE_SECOND_NUMBER) + ConstantDef.EXCEL_SUFFIX_FORMAT;
+        // 写到本地,拼凑本地路径
+        String localPath = preLocalPath + fileName + ".xls";
+        String ossPath = String.format(ConstantDef.BIG_DATA_EXCEL_FILE_PATH, FormatUtil.formatDate(new Date(), "yyyy-MM"));
+        String ossFileName = fileName + suffixFormat + ".xls";
+        try {
+            byte[] bytes = FileToByte(localPath);
+            if (Checker.isNone(bytes)) {
+                return "";
+            }
+            UploadFileRequest rest = UploadFileRequest.newBuilder()
+                    .setFilename(ossFileName)
+                    .setVpath(ossPath)
+                    .setDatas(ByteString.copyFrom(bytes))
+                    .build();
+            UploadFileResponse resp = fileServiceBlockingStub.uploadFile(rest);
+            return resp.getFileUrl();
+        } catch (Exception e) {
+            e.printStackTrace();
+            return "";
+        }
+    }
+
+    public static byte[] FileToByte(String filePath) {
+        byte[] buffer = null;
+        try {
+            File file = new File(filePath);
+            FileInputStream fis = new FileInputStream(file);
+            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            byte[] b = new byte[1024];
+            int n;
+            while ((n = fis.read(b)) != -1) {
+                bos.write(b, 0, n);
+            }
+            fis.close();
+            bos.close();
+            buffer = bos.toByteArray();
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return buffer;
+    }
+
+    @RequestMapping({"/test1"})
+    public String test1() {
+        // 本地文件上传到oss,文件名带后缀
+        String fileName = "订餐订单列表";
+        // 前缀(路径)
+        String preLocalPath = ConstantDef.LOCAL_DOWNLOAD_FILE_PATH;
+        // 后缀(下载时间和格式)
+        String suffixFormat = FormatUtil.formatDate(new Date(), FormatUtil.FORMAT_DATE_SECOND_NUMBER) + ConstantDef.EXCEL_SUFFIX_FORMAT;
+        // 写到本地,拼凑本地路径
+        String localPath = preLocalPath + fileName + ".xls";
+        String ossPath = String.format(ConstantDef.BIG_DATA_EXCEL_FILE_PATH, FormatUtil.formatDate(new Date(), "yyyy-MM"));
+        String ossFileName = ossPath+"/"+ fileName + suffixFormat + ".xls";
+        String url = ossSettring.uploadFile(localPath, ossFileName);
+        System.out.println("------------");
+        System.out.println(url);
+        return url;
+    }
+
+}

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

@@ -1,7 +1,7 @@
 server.port=7678
 
 #前缀
-#server.contextPath=/downloadService
+server.contextPath=/downloadService
 
 spring.jpa.hibernate.ddl-auto=none