chao пре 3 година
родитељ
комит
61d48710cd

+ 7 - 0
pom.xml

@@ -98,6 +98,13 @@
             <groupId>redis.clients</groupId>
             <artifactId>jedis</artifactId>
         </dependency>
+        <!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
+        <dependency>
+            <groupId>com.github.tobato</groupId>
+            <artifactId>fastdfs-client</artifactId>
+            <version>1.27.2</version>
+        </dependency>
+
         <!-- https://mvnrepository.com/artifact/org.apache.rocketmq/rocketmq-spring-boot-starter -->
         <!-- RocketMQ starter -->
         <dependency>

+ 39 - 0
src/main/java/com/caimei365/tools/controller/UploadApi.java

@@ -0,0 +1,39 @@
+package com.caimei365.tools.controller;
+
+import com.caimei365.tools.model.ResponseJson;
+import com.caimei365.tools.service.UploadService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiOperation;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpHeaders;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * Description
+ *
+ * @author : Charles
+ * @date : 2021/10/25
+ */
+@Slf4j
+@Api(tags="文件上传API")
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/tools")
+public class UploadApi {
+
+    private final UploadService uploadService;
+    /**
+     * 图片上传
+     */
+    @ApiOperation("图片上传(旧:/formData/MultiPictareaddData)")
+    @ApiImplicitParam(required = true, name = "file", value = "图片")
+    @RequestMapping("/upload/image")
+    public ResponseJson<String> bulkImageUpload(MultipartFile[] file, @RequestHeader HttpHeaders headers) {
+        return uploadService.bulkImageUpload(file, headers);
+    }
+}

+ 18 - 0
src/main/java/com/caimei365/tools/service/UploadService.java

@@ -0,0 +1,18 @@
+package com.caimei365.tools.service;
+
+import com.caimei365.tools.model.ResponseJson;
+import org.springframework.http.HttpHeaders;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * Description
+ *
+ * @author : Charles
+ * @date : 2021/10/25
+ */
+public interface UploadService {
+    /**
+     * 图片上传
+     */
+    ResponseJson<String> bulkImageUpload(MultipartFile[] file, HttpHeaders headers);
+}

+ 83 - 0
src/main/java/com/caimei365/tools/service/impl/UploadServiceImpl.java

@@ -0,0 +1,83 @@
+package com.caimei365.tools.service.impl;
+
+import com.caimei365.tools.model.ResponseJson;
+import com.caimei365.tools.service.UploadService;
+import com.caimei365.tools.utils.FastDfsUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.io.IOException;
+import java.util.UUID;
+
+/**
+ * Description
+ *
+ * @author : Charles
+ * @date : 2021/10/25
+ */
+@Slf4j
+@Service
+public class UploadServiceImpl implements UploadService {
+    @Value("${caimei.imageDomain}")
+    private String imageDomain;
+    @Value("${spring.cloud.config.profile}")
+    private String profile;
+    @Resource
+    private FastDfsUtil fastDfsUtil;
+
+    /**
+     * 图片上传
+     */
+    @Override
+    public ResponseJson<String> bulkImageUpload(MultipartFile[] file, HttpHeaders headers){
+        // 打印IP
+        String ip = headers.getFirst("X-CLIENT-IP");
+        log.info("【图片上传】 X-CLIENT-IP : " + ip);
+        if (file != null && file.length > 0) {
+            try {
+                StringBuilder fileUrl = new StringBuilder();
+                for (MultipartFile fileItem : file) {
+                    String url = saveFile(fileItem);
+                    fileUrl.append(imageDomain).append("/").append(url);
+                }
+                log.info("【图片上传】>>>>>>>>>>>>>>>>上传成功:" + fileUrl);
+                return ResponseJson.success("上传成功", fileUrl.toString());
+            } catch (IOException e) {
+                log.error("【图片上传】>>>>>>>>>>>>>>>>上传失败:" + e);
+                return ResponseJson.error("请传入图片!",null);
+            }
+        } else {
+            return ResponseJson.error("请传入图片!",null);
+        }
+    }
+
+    /**
+     * 保存文件
+     */
+    private String saveFile(MultipartFile file) throws IOException {
+        String originalFilename = file.getOriginalFilename();
+        String randomStr = UUID.randomUUID().toString();
+        assert originalFilename != null;
+        int index = originalFilename.lastIndexOf(".");
+        String name = originalFilename.substring(index);
+        String filePath = "/mnt/newdatadrive/data/runtime/cloud-instance/server-tools/";
+        if ("dev".equals(profile)){
+            filePath = "D:\\";
+        }
+        filePath += "\\" + randomStr + name;
+        // 临时图片
+        File tempFile = new File(filePath);
+        file.transferTo(tempFile);
+        log.info("【图片上传】>>>>>>>>>>>>>>>>图片临时路径:" + filePath);
+        String fileUrl = fastDfsUtil.uploadFile(filePath);
+        // 删除临时图片
+        boolean delete = tempFile.delete();
+        log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时图片:" + delete);
+        return fileUrl;
+    }
+}

+ 50 - 0
src/main/java/com/caimei365/tools/utils/FastDfsUtil.java

@@ -0,0 +1,50 @@
+package com.caimei365.tools.utils;
+
+import com.github.tobato.fastdfs.domain.fdfs.StorePath;
+import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
+import com.github.tobato.fastdfs.service.FastFileStorageClient;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.FilenameUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.io.*;
+
+/**
+ * Description
+ *
+ * @author : Charles
+ * @date : 2021/10/25
+ */
+@Component
+public class FastDfsUtil {
+    @Resource
+    private FastFileStorageClient storageClient;
+
+
+    // 文件上传
+    public String uploadFile(String path) throws FileNotFoundException {
+        File file = new File(path);
+        InputStream input = new FileInputStream(file);
+        long size = FileUtils.sizeOf(file);
+        String name = file.getName();
+        String fileName = name.substring(name.lastIndexOf("/") + 1);
+        StorePath storePath = storageClient.uploadFile(input, size, FilenameUtils.getExtension(fileName), null);
+        return storePath.getFullPath();
+    }
+
+    // 文件下载
+    public boolean downloadFile(String path, String downloadFilePath) throws IOException {
+        File file = new File(downloadFilePath);
+        FileOutputStream outputStream = null;
+        // fastdfs 文件读取
+        String filepath = path.substring(path.lastIndexOf("group1/") + 7);
+        DownloadByteArray callback = new DownloadByteArray();
+        byte[] content = storageClient.downloadFile("group1", filepath, callback);
+        // 数据写入指定文件夹中
+        outputStream = new FileOutputStream(file);
+        outputStream.write(content);
+        return true;
+    }
+}