From ddfbc40f9ca8546a2c34865abef51630f054d5e9 Mon Sep 17 00:00:00 2001
From: liuhaonan <31457034@qq.com>
Date: 星期一, 07 十一月 2022 14:00:45 +0800
Subject: [PATCH] changes

---
 sandu-common/src/main/java/com/sandu/common/file/impl/AliOssFileServiceImpl.java |  126 +++++++++++++++++++++++++++++++++++------
 1 files changed, 106 insertions(+), 20 deletions(-)

diff --git a/sandu-common/src/main/java/com/sandu/common/file/impl/AliOssFileServiceImpl.java b/sandu-common/src/main/java/com/sandu/common/file/impl/AliOssFileServiceImpl.java
index a158728..97df32c 100644
--- a/sandu-common/src/main/java/com/sandu/common/file/impl/AliOssFileServiceImpl.java
+++ b/sandu-common/src/main/java/com/sandu/common/file/impl/AliOssFileServiceImpl.java
@@ -13,15 +13,18 @@
 import com.sandu.common.execption.BusinessException;
 import com.sandu.common.file.FileUploadDto;
 import com.sandu.common.file.IFileUpload;
-import lombok.AllArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.imageio.ImageIO;
 import java.awt.image.BufferedImage;
 import java.io.ByteArrayInputStream;
+import java.io.File;
 import java.io.IOException;
+import java.math.BigInteger;
+import java.security.MessageDigest;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
 
@@ -33,10 +36,15 @@
 @Component
 public class AliOssFileServiceImpl implements IFileUpload {
 
-    private final String endPoint="oss-cn-shanghai.aliyuncs.com";
-    private final String keyId="LTAI5tPdpt5wvJyLipRijFSP";
-    private final String keySecret="1ahYfCKd0yTddsUnuDLQzI23MLh4VQ";
-    private final String bucketName= "ximonsmart";
+    @Value("${oss-conf.end-point}")
+    private String endPoint;
+    @Value("${oss-conf.key-id}")
+    private String keyId;
+    @Value("${oss-conf.key-secret}")
+    private String keySecret;
+    @Value("${oss-conf.bucket-name}")
+    private String bucketName;
+
     private String host;
 
     @Override
@@ -45,8 +53,9 @@
         long size = multipartFile.getSize();
         String suffix = FileUtil.getSuffix(originalFilename);
         String dayStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
-        String fileName = dayStr + UUID.fastUUID()+ "." + suffix;
+        String fileName = dayStr + UUID.fastUUID() + "." + suffix;
 
+        String md5 = getMD5(multipartFile);
         FileUploadDto uploadDto = new FileUploadDto();
         OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);
         try {
@@ -59,6 +68,74 @@
             }
             //涓婁紶鏂囦欢
             PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileName, new ByteArrayInputStream(multipartFile.getBytes())));
+            //璁剧疆鏉冮檺 杩欓噷鏄叕寮�璇�
+//            ossClient.setBucketAcl(ossProperties.getBucketName(), CannedAccessControlList.PublicRead);
+
+            if (result != null) {
+                String url = "";
+                // https://BucketName.Endpoint/ObjectName
+                if (StrUtil.isBlank(host)) {
+                    url = "https://" + bucketName + "." + endPoint + "/" + fileName;
+                } else {
+                    if (!host.endsWith("/")) {
+                        url = host + "/" + fileName;
+                    } else {
+                        url = host + fileName;
+                    }
+                }
+
+                uploadDto.setFileUrl(url);
+            }
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            throw new BusinessException(e.getMessage());
+        } finally {
+            //鍏抽棴
+            ossClient.shutdown();
+        }
+
+        uploadDto.setOriginName(originalFilename);
+        uploadDto.setFileName(fileName);
+        uploadDto.setFileType(FileUtil.extName(originalFilename));
+        uploadDto.setStorageType(FileStorageEnums.ALIBABA.getCode());
+        uploadDto.setFileSize(size);
+        uploadDto.setMd5(md5);
+
+        if (IMAGE_SUFFIX_LIST.contains(uploadDto.getFileType())) {
+            BufferedImage img = null;
+            try {
+                img = ImageIO.read(multipartFile.getInputStream());
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+            if (img != null && img.getWidth() >= 0 && img.getHeight() >= 0) {
+                uploadDto.setWidth(img.getWidth());
+                uploadDto.setHeight(img.getHeight());
+            }
+        }
+
+        return uploadDto;
+    }
+
+    public FileUploadDto uploadFile(File multipartFile) {
+        String originalFilename = multipartFile.getName();
+//        long size = multipartFile.get();
+        String suffix = FileUtil.getSuffix(originalFilename);
+        String dayStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
+        String fileName = dayStr + UUID.fastUUID() + "." + suffix;
+
+        FileUploadDto uploadDto = new FileUploadDto();
+        OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);
+        try {
+            //瀹瑰櫒涓嶅瓨鍦紝灏卞垱寤�
+            if (!ossClient.doesBucketExist(bucketName)) {
+                ossClient.createBucket(bucketName);
+                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
+                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
+                ossClient.createBucket(createBucketRequest);
+            }
+            //涓婁紶鏂囦欢
+            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileName, multipartFile));
             //璁剧疆鏉冮檺 杩欓噷鏄叕寮�璇�
 //            ossClient.setBucketAcl(ossProperties.getBucketName(), CannedAccessControlList.PublicRead);
 
@@ -88,21 +165,30 @@
         uploadDto.setFileName(fileName);
         uploadDto.setFileType(FileUtil.extName(originalFilename));
         uploadDto.setStorageType(FileStorageEnums.ALIBABA.getCode());
-        uploadDto.setFileSize(size);
-
-        if (IMAGE_SUFFIX_LIST.contains(uploadDto.getFileType())) {
-            BufferedImage img = null;
-            try {
-                img = ImageIO.read(multipartFile.getInputStream());
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-            if (img != null && img.getWidth() >= 0 && img.getHeight() >= 0) {
-                uploadDto.setWidth(img.getWidth());
-                uploadDto.setHeight(img.getHeight());
-            }
-        }
 
         return uploadDto;
     }
+
+    /**
+     * 鑾峰彇涓婁紶鏂囦欢鐨凪D5鍊�
+     *
+     * @param file
+     * @return
+     */
+    public String getMD5(MultipartFile file) {
+
+        try {
+            byte[] uploadBytes = file.getBytes();
+            MessageDigest md5 = MessageDigest.getInstance("MD5");
+            byte[] digest = md5.digest(uploadBytes);
+            String hashString = new BigInteger(1, digest).toString(16);
+            if (hashString.length() % 2 != 0) {
+                hashString = "0" + hashString;
+            }
+            return hashString;
+        } catch (Exception e) {
+        }
+        return null;
+    }
+
 }

--
Gitblit v1.9.3