From 5f5db5ddcccd858e45bf9e9b92f55646218d4643 Mon Sep 17 00:00:00 2001
From: Junjie <fallin.jie@qq.com>
Date: 星期二, 07 十一月 2023 10:29:59 +0800
Subject: [PATCH] #

---
 src/main/java/com/zy/crm/common/service/OssService.java |  113 +++++++++++++++++++++++++++++++-------------------------
 1 files changed, 63 insertions(+), 50 deletions(-)

diff --git a/src/main/java/com/zy/crm/common/service/OssService.java b/src/main/java/com/zy/crm/common/service/OssService.java
index fc3ce79..c947e85 100644
--- a/src/main/java/com/zy/crm/common/service/OssService.java
+++ b/src/main/java/com/zy/crm/common/service/OssService.java
@@ -3,6 +3,8 @@
 import com.aliyun.oss.OSSClient;
 import com.aliyun.oss.model.OSSObject;
 import com.aliyun.oss.model.ObjectMetadata;
+import com.aliyun.oss.model.PutObjectRequest;
+import com.aliyun.oss.model.PutObjectResult;
 import com.core.common.SnowflakeIdWorker;
 import com.core.exception.CoolException;
 import lombok.Data;
@@ -10,14 +12,16 @@
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.io.InputStreamResource;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
+import java.io.*;
 import java.net.URL;
 import java.nio.file.Path;
+import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.nio.file.StandardCopyOption;
 import java.nio.file.Files;
@@ -33,7 +37,7 @@
 
     private static Logger log = LoggerFactory.getLogger(OssService.class);
 
-    private static final String OSS_ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com";
+    private static final String OSS_ENDPOINT = "http://zhongyang-ftpserver.oss-cn-hangzhou-internal.aliyuncs.com";
 
     @Value("${aliyun.oss.id}")
     private String accessKeyId;
@@ -54,6 +58,7 @@
      * 涓婁紶OSS鏂囦欢
      * @return the url
      */
+    @Deprecated
     public String upload(InputStream inputStream, String suffix){
         if(suffix.trim().equals("file")){
             suffix="jpg";
@@ -82,18 +87,18 @@
         }
         throw new CoolException("500-涓婁紶澶辫触");
     }
-    public String upload(InputStream inputStream, String suffix,String contentType){
-        if(suffix.trim().equals("file")){
-            suffix="jpg";
-        }
+
+    @Deprecated
+    public String upload(InputStream inputStream, String filename, String contentType) {
         OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
         String name = "";
         try {
             if (!ossClient.doesBucketExist(bucket)) {
                 ossClient.createBucket(bucket);
-                log.info("鎮ㄧ殑Bucket涓嶅瓨鍦紝鍒涘缓Bucket锛歿}",bucket);
+                log.info("鎮ㄧ殑Bucket涓嶅瓨鍦紝鍒涘缓Bucket锛歿}", bucket);
             }
-            name = String.valueOf(snowflakeIdWorker.nextId()).concat(".").concat(suffix);
+            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
+            name = format.format(new Date()) + "_" + filename;
             // 娣诲姞 ContentType
             ObjectMetadata objectMetadata = new ObjectMetadata();
 //            objectMetadata.setContentType("image/jpg");
@@ -103,8 +108,8 @@
             URL url = ossClient.generatePresignedUrl(bucket, name, expiration);
             log.info("OSS鏂囦欢涓婁紶鎴愬姛: {}", name);
 //            return String.valueOf(url);
-            return "http://zhongyang-ftpserver.oss-cn-hangzhou.aliyuncs.com/"+name;
-        } catch (Exception e){
+            return "http://zhongyang-ftpserver.oss-cn-hangzhou.aliyuncs.com/" + name;
+        } catch (Exception e) {
             e.printStackTrace();
         } finally {
             ossClient.shutdown();
@@ -112,54 +117,62 @@
         throw new CoolException("500-涓婁紶澶辫触");
     }
 
+    @Deprecated
     public String upload(InputStream inputStream) {
         return upload(inputStream, ".jpg");
     }
 
     /**
-     * 涓嬭浇OSS鏂囦欢
+     * 鏂囦欢涓婁紶
+     * @param filePath OSS璺緞
+     * @param file 鏂囦欢File
      */
-//    public void download(String name) {
+    public boolean uploadFile(String filePath, File file) {
+        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
+        // 鍒涘缓PutObjectRequest瀵硅薄銆�
+        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, filePath, file);
+        // 涓婁紶鏂囦欢銆�
+        PutObjectResult result = ossClient.putObject(putObjectRequest);
+        return true;
+    }
+
+//    /**
+//     * 涓嬭浇鏂囦欢
+//     * @param filePath OSS璺緞
+//     */
+//    public ResponseEntity<InputStreamResource> downloadFile(String filePath) throws IOException {
 //        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
-//        try {
-//            OSSObject ossObject = ossClient.getObject(bucket, name);
-//            InputStream inputStream = ossObject.getObjectContent();
-//            // do transfer
-//            inputStream.close();
-//            log.info("OSS鏂囦欢涓嬭浇鎴愬姛: {}", name);
-//        } catch (Exception e){
-//            e.printStackTrace();
-//        } finally {
-//            ossClient.shutdown();
-//        }
+//        OSSObject ossObject = ossClient.getObject(bucket, filePath);
+//        InputStream inputStream = ossObject.getObjectContent();
+//
+//        // 鍒涘缓鍝嶅簲瀹炰綋锛屽皢杈撳嚭娴佷綔涓烘枃浠跺唴瀹硅繑鍥�
+//        HttpHeaders headers = new HttpHeaders();
+//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
+//        headers.setContentDispositionFormData("attachment", "output.docx");
+//        InputStreamResource resource = new InputStreamResource(convertToByteArrayInputStream(inputStream));
+//        return ResponseEntity.ok()
+//                .headers(headers)
+//                .body(resource);
 //    }
 
+    public static ByteArrayInputStream convertToByteArrayInputStream(InputStream inputStream) throws IOException {
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+        byte[] buffer = new byte[4096];
+        int bytesRead;
+        while ((bytesRead = inputStream.read(buffer)) != -1) {
+            outputStream.write(buffer, 0, bytesRead);
+        }
+        byte[] data = outputStream.toByteArray();
+        return new ByteArrayInputStream(data);
+    }
+
+    @Deprecated
     public String download(String name) {
         OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
-        try {
-            OSSObject ossObject = ossClient.getObject(bucket, name);
-            InputStream inputStream = ossObject.getObjectContent();
-
-            // 鑾峰彇榛樿涓嬭浇鐩綍
-            String defaultDownloadDir = System.getProperty("user.home") + "/Downloads";
-
-            // 鍒涘缓鏂囦欢淇濆瓨璺緞
-            Path filePath = Paths.get(defaultDownloadDir, name);
-
-            // 灏嗚緭鍏ユ祦澶嶅埗鍒版枃浠�
-            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
-
-            // 鍏抽棴杈撳叆娴�
-            inputStream.close();
-
-            log.info("OSS鏂囦欢涓嬭浇鎴愬姛锛屼繚瀛樿矾寰�: {}", filePath);
-            return ""+filePath;
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            ossClient.shutdown();
-        }
-        return "";
+        //鑾峰彇涓存椂涓嬭浇閾炬帴
+        URL url = ossClient.generatePresignedUrl(bucket, name, new Date(new Date().getTime() + 3600 * 1000));
+        log.info("OSS鏂囦欢涓存椂涓嬭浇璺緞锛孶RL璺緞: {}", url);
+        return url.toString();
     }
 
     /**

--
Gitblit v1.9.1