Browse Source

优化文件操作工具类;新增本地文件上传实现;

woody 1 year ago
parent
commit
cd4bf692b2

+ 111 - 24
framework-base/src/main/java/com/chelvc/framework/base/util/FileUtils.java

@@ -1,14 +1,19 @@
 package com.chelvc.framework.base.util;
 
+import java.awt.*;
+import java.awt.image.BufferedImage;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
 import java.io.Reader;
 import java.io.Writer;
-import java.util.UUID;
 import java.util.function.Consumer;
 
 import lombok.NonNull;
@@ -30,27 +35,34 @@ public final class FileUtils {
     /**
      * 文件上传目录
      */
-    public static final String UPLOAD = TEMPORARY + "/upload";
+    public static final String UPLOAD = new File(TEMPORARY, "upload").getPath();
 
     /**
      * 文件导出目录
      */
-    public static final String EXPORT = TEMPORARY + "/export";
+    public static final String EXPORT = new File(TEMPORARY, "export").getPath();
 
     /**
      * 文件下载目录
      */
-    public static final String DOWNLOAD = TEMPORARY + "/download";
+    public static final String DOWNLOAD = new File(TEMPORARY, "download").getPath();
 
     static {
-        // 初始化文件目录
-        if (!new File(UPLOAD).mkdirs()) {
+        // 初始化文件上传目录
+        File upload = new File(UPLOAD);
+        if (!upload.exists() && !upload.mkdirs()) {
             log.warn("Make upload dir failed: {}", UPLOAD);
         }
-        if (!new File(EXPORT).mkdirs()) {
+
+        // 初始化文件导出目录
+        File export = new File(EXPORT);
+        if (!export.exists() && !export.mkdirs()) {
             log.warn("Make export dir failed: {}", EXPORT);
         }
-        if (!new File(DOWNLOAD).mkdirs()) {
+
+        // 初始化文件下载目录
+        File download = new File(DOWNLOAD);
+        if (!download.exists() && !download.mkdirs()) {
             log.warn("Make download dir failed: {}", DOWNLOAD);
         }
     }
@@ -86,29 +98,38 @@ public final class FileUtils {
     }
 
     /**
-     * 生成文件唯一名称
+     * 获取文件后缀名
      *
      * @param file 文件对象
-     * @return 文件名称
+     * @return 后缀名
      */
-    public static String generateUniqueName(@NonNull File file) {
-        return generateUniqueName(file.getName());
+    public static String getSuffix(@NonNull File file) {
+        return getSuffix(file.getName());
     }
 
     /**
-     * 生成文件唯一名称
+     * 获取文件后缀名
      *
-     * @param filename 文件名
-     * @return 文件名称
-     */
-    public static String generateUniqueName(@NonNull String filename) {
-        int separatorIndex = filename.indexOf('.');
-        String suffix = separatorIndex < 0 ? null : filename.substring(separatorIndex + 1);
-        String unique = UUID.randomUUID().toString();
-        if (StringUtils.isEmpty(suffix)) {
-            return unique;
-        }
-        return unique + "." + suffix;
+     * @param filename 文件名称
+     * @return 后缀名
+     */
+    public static String getSuffix(@NonNull String filename) {
+        int separator = filename.indexOf('.');
+        return separator < 0 ? null : StringUtils.ifEmpty(filename.substring(separator + 1), (String) null);
+    }
+
+    /**
+     * 图片压缩
+     *
+     * @param image 图片对象
+     * @return 图片对象
+     */
+    public static BufferedImage compress(@NonNull BufferedImage image) {
+        int width = image.getWidth(null);
+        int height = image.getHeight(null);
+        BufferedImage compress = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+        compress.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
+        return compress;
     }
 
     /**
@@ -243,6 +264,72 @@ public final class FileUtils {
         }
     }
 
+    /**
+     * 将文件写入文件
+     *
+     * @param out 输出文件
+     * @param in  输入文件
+     */
+    public static void write(@NonNull File out, @NonNull File in) {
+        try {
+            try (OutputStream output = new FileOutputStream(out)) {
+                write(output, in);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 将输入流写入文件
+     *
+     * @param file  文件对象
+     * @param input 输入流
+     */
+    public static void write(@NonNull File file, @NonNull InputStream input) {
+        try {
+            try (OutputStream output = new FileOutputStream(file)) {
+                write(output, input);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 将文件写入输入流
+     *
+     * @param output 输出流
+     * @param file   文件对象
+     */
+    public static void write(@NonNull OutputStream output, @NonNull File file) {
+        try {
+            try (InputStream input = new FileInputStream(file)) {
+                write(output, input);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 将输入流写入输出流
+     *
+     * @param output 输出流
+     * @param input  输入流
+     */
+    public static void write(@NonNull OutputStream output, @NonNull InputStream input) {
+        int len;
+        byte[] buffer = new byte[1024];
+        try {
+            while ((len = input.read(buffer)) > -1) {
+                output.write(buffer, 0, len);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     /**
      * 删除文件
      *

+ 3 - 13
framework-upload/src/main/java/com/chelvc/framework/upload/UploadHandler.java

@@ -23,21 +23,11 @@ public interface UploadHandler {
     /**
      * 文件上传
      *
-     * @param stream   文件流
-     * @param filename 文件
+     * @param stream 文件流
+     * @param suffix 后缀
      * @return 文件访问地址
      */
-    String upload(InputStream stream, String filename);
-
-    /**
-     * 文件上传
-     *
-     * @param stream   文件流
-     * @param filename 文件名
-     * @param size     文件大小
-     * @return 文件访问地址
-     */
-    String upload(InputStream stream, String filename, long size);
+    String upload(InputStream stream, String suffix);
 
     /**
      * 图片上传

+ 18 - 23
framework-upload/src/main/java/com/chelvc/framework/upload/support/StandardUploadHandler.java

@@ -2,10 +2,14 @@ package com.chelvc.framework.upload.support;
 
 import java.awt.image.BufferedImage;
 import java.io.File;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import javax.imageio.ImageIO;
 
+import com.chelvc.framework.base.util.FileUtils;
 import com.chelvc.framework.base.util.HttpUtils;
+import com.chelvc.framework.base.util.StringUtils;
 import com.chelvc.framework.upload.UploadHandler;
 import com.chelvc.framework.upload.config.StandardUploadProperties;
 import lombok.NonNull;
@@ -28,37 +32,28 @@ import org.springframework.stereotype.Component;
 public class StandardUploadHandler implements UploadHandler {
     private final StandardUploadProperties properties;
 
-    /**
-     * 将唯一标识转换成资源地址
-     *
-     * @param key 唯一标识
-     * @return 资源地址
-     */
-    private String key2uri(String key) {
-//        return String.format(
-//                "https://%s.cos.%s.myqcloud.com/%s",
-//                this.properties.getBucket(), this.properties.getRegion(), key
-//        );
-        return HttpUtils.url(this.properties.getDomain(), key);
-    }
-
     @Override
     public String upload(@NonNull File file) {
-        return null;
-    }
-
-    @Override
-    public String upload(@NonNull InputStream stream, @NonNull String filename) {
-        return null;
+        String suffix = FileUtils.getSuffix(file);
+        String filename = StringUtils.uuid() + StringUtils.ifEmpty(suffix, "." + suffix);
+        FileUtils.write(new File(this.properties.getPath(), filename), file);
+        return HttpUtils.url(this.properties.getDomain(), filename);
     }
 
     @Override
-    public String upload(@NonNull InputStream stream, @NonNull String filename, long size) {
-        return null;
+    public String upload(@NonNull InputStream stream, @NonNull String suffix) {
+        String filename = StringUtils.uuid() + StringUtils.ifEmpty(suffix, "." + suffix);
+        FileUtils.write(new File(this.properties.getPath(), filename), stream);
+        return HttpUtils.url(this.properties.getDomain(), filename);
     }
 
     @Override
     public String upload(@NonNull BufferedImage image) throws IOException {
-        return null;
+        image = FileUtils.compress(image);
+        String filename = StringUtils.uuid() + ".jpeg";
+        try (FileOutputStream output = new FileOutputStream(new File(this.properties.getPath(), filename))) {
+            ImageIO.write(image, "jpeg", output);
+        }
+        return HttpUtils.url(this.properties.getDomain(), filename);
     }
 }

+ 16 - 45
framework-upload/src/main/java/com/chelvc/framework/upload/support/TencentUploadHandler.java

@@ -1,6 +1,5 @@
 package com.chelvc.framework.upload.support;
 
-import java.awt.*;
 import java.awt.image.BufferedImage;
 import java.io.File;
 import java.io.FileOutputStream;
@@ -10,13 +9,13 @@ import java.util.UUID;
 import javax.imageio.ImageIO;
 
 import com.chelvc.framework.base.util.FileUtils;
+import com.chelvc.framework.base.util.StringUtils;
 import com.chelvc.framework.upload.UploadHandler;
 import com.chelvc.framework.upload.config.TencentUploadProperties;
 import com.qcloud.cos.COSClient;
 import com.qcloud.cos.model.ObjectMetadata;
 import lombok.NonNull;
 import lombok.RequiredArgsConstructor;
-import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
 import org.springframework.stereotype.Component;
@@ -27,7 +26,6 @@ import org.springframework.stereotype.Component;
  * @author Woody
  * @date 2023/4/5
  */
-@Slf4j
 @Component
 @ConditionalOnBean(TencentUploadProperties.class)
 @RequiredArgsConstructor(onConstructor = @__(@Autowired))
@@ -36,67 +34,40 @@ public class TencentUploadHandler implements UploadHandler {
     private final TencentUploadProperties properties;
 
     /**
-     * 将唯一标识转换成资源地址
+     * 将文件名称转换成URL地址
      *
-     * @param key 唯一标识
-     * @return 资源地址
+     * @param filename 文件名称
+     * @return URL地址
      */
-    private String key2uri(String key) {
+    private String name2url(String filename) {
         return String.format(
                 "https://%s.cos.%s.myqcloud.com/%s",
-                this.properties.getBucket(), this.properties.getRegion(), key
+                this.properties.getBucket(), this.properties.getRegion(), filename
         );
     }
 
-    /**
-     * 文件上传
-     *
-     * @param stream   文件流
-     * @param filename 文件名
-     * @param metadata 文件信息
-     * @return 文件访问地址
-     */
-    private String upload(InputStream stream, String filename, ObjectMetadata metadata) {
-        if (log.isDebugEnabled()) {
-            log.debug("Uploading stream: {}", filename);
-        }
-        String key = FileUtils.generateUniqueName(filename);
-        this.client.putObject(this.properties.getBucket(), key, stream, metadata);
-        return this.key2uri(key);
-    }
-
     @Override
     public String upload(@NonNull File file) {
-        if (log.isDebugEnabled()) {
-            log.debug("Uploading file: {}", file);
-        }
-        String key = FileUtils.generateUniqueName(file);
-        this.client.putObject(this.properties.getBucket(), key, file);
-        return this.key2uri(key);
-    }
-
-    @Override
-    public String upload(@NonNull InputStream stream, @NonNull String filename) {
-        return this.upload(stream, filename, new ObjectMetadata());
+        String suffix = FileUtils.getSuffix(file);
+        String filename = StringUtils.uuid() + StringUtils.ifEmpty(suffix, "." + suffix);
+        this.client.putObject(this.properties.getBucket(), filename, file);
+        return this.name2url(filename);
     }
 
     @Override
-    public String upload(@NonNull InputStream stream, @NonNull String filename, long size) {
-        ObjectMetadata metadata = new ObjectMetadata();
-        metadata.setContentLength(size);
-        return this.upload(stream, filename, metadata);
+    public String upload(@NonNull InputStream stream, @NonNull String suffix) {
+        String filename = StringUtils.uuid() + StringUtils.ifEmpty(suffix, "." + suffix);
+        this.client.putObject(this.properties.getBucket(), filename, stream, new ObjectMetadata());
+        return this.name2url(filename);
     }
 
     @Override
     public String upload(@NonNull BufferedImage image) throws IOException {
         // 图片压缩
-        int width = image.getWidth(null);
-        int height = image.getHeight(null);
-        BufferedImage compress = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
-        compress.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
+        image = FileUtils.compress(image);
         File target = new File(FileUtils.getUploadDirectory(), UUID.randomUUID().toString() + ".jpeg");
         try (FileOutputStream output = new FileOutputStream(target)) {
-            ImageIO.write(compress, "jpeg", output);
+            ImageIO.write(image, "jpeg", output);
         }
 
         // 上传图片