Kaynağa Gözat

智能预问诊文件删除功能

gaodm 6 yıl önce
ebeveyn
işleme
e7f3cd8e87

+ 7 - 0
config-server/src/main/resources/shared/prec-service-dev.yml

@@ -95,3 +95,10 @@ mybatis-plus:
     map-underscore-to-camel-case: true
     cache-enabled: false
 
+fastdfs:
+  connect_timeout_in_seconds: 60
+  network_timeout_in_seconds: 60
+  charset: UTF-8
+  http_tracker_http_port: 8080
+  http_anti_steal_token: no
+  tracker_servers: 192.168.2.236:22122

+ 7 - 0
config-server/src/main/resources/shared/prec-service-local.yml

@@ -95,3 +95,10 @@ mybatis-plus:
     map-underscore-to-camel-case: true
     cache-enabled: false
 
+fastdfs:
+  connect_timeout_in_seconds: 60
+  network_timeout_in_seconds: 60
+  charset: UTF-8
+  http_tracker_http_port: 8080
+  http_anti_steal_token: no
+  tracker_servers: 192.168.2.236:22122

+ 7 - 0
config-server/src/main/resources/shared/prec-service-pro.yml

@@ -95,3 +95,10 @@ mybatis-plus:
     map-underscore-to-camel-case: true
     cache-enabled: false
 
+fastdfs:
+  connect_timeout_in_seconds: 60
+  network_timeout_in_seconds: 60
+  charset: UTF-8
+  http_tracker_http_port: 8080
+  http_anti_steal_token: no
+  tracker_servers: 192.168.2.236:22122

+ 8 - 0
config-server/src/main/resources/shared/prec-service-test.yml

@@ -95,3 +95,11 @@ mybatis-plus:
     map-underscore-to-camel-case: true
     cache-enabled: false
 
+
+fastdfs:
+  connect_timeout_in_seconds: 60
+  network_timeout_in_seconds: 60
+  charset: UTF-8
+  http_tracker_http_port: 8080
+  http_anti_steal_token: no
+  tracker_servers: 192.168.2.241:22122

+ 17 - 0
prec-service/pom.xml

@@ -154,6 +154,23 @@
             <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>net.oschina.zcx7878</groupId>
+            <artifactId>fastdfs-client-java</artifactId>
+            <version>1.27.0.0</version>
+        </dependency>
+        <!-- 文件上传相关架包 -->
+        <dependency>
+            <groupId>commons-fileupload</groupId>
+            <artifactId>commons-fileupload</artifactId>
+            <version>1.3.1</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <version>2.4</version>
+        </dependency>
+
     </dependencies>
 
     <build>

+ 119 - 0
prec-service/src/main/java/com/diagbot/client/fastdfs/FastDFSClient.java

@@ -0,0 +1,119 @@
+package com.diagbot.client.fastdfs;
+
+import org.csource.common.NameValuePair;
+import org.csource.fastdfs.ClientGlobal;
+import org.csource.fastdfs.FileInfo;
+import org.csource.fastdfs.ServerInfo;
+import org.csource.fastdfs.StorageClient;
+import org.csource.fastdfs.StorageServer;
+import org.csource.fastdfs.TrackerClient;
+import org.csource.fastdfs.TrackerServer;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * @Description: FastDFS 客户端
+ * @author: gaodm
+ * @time: 2018/11/13 13:55
+ */
+public class FastDFSClient {
+    private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
+
+    public static String[] upload(FastDFSFile file) {
+        logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
+
+        // 设置元信息
+        NameValuePair[] meta_list = new NameValuePair[3];
+        meta_list[0] = new NameValuePair("name", file.getName());
+        meta_list[1] = new NameValuePair("ext", file.getExt());
+        meta_list[2] = new NameValuePair("author", file.getAuthor());
+
+        long startTime = System.currentTimeMillis();
+        String[] uploadResults = null;
+        StorageClient storageClient = null;
+        try {
+            storageClient = getTrackerClient();
+            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
+        } catch (IOException e) {
+            logger.error("IO Exception when uploadind the file:" + file.getName(), e);
+        } catch (Exception e) {
+            logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
+        }
+        logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
+
+        if (uploadResults == null && storageClient != null) {
+            logger.error("upload file fail, error code:" + storageClient.getErrorCode());
+        }
+        String groupName = uploadResults[0];
+        String remoteFileName = uploadResults[1];
+
+        logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
+        return uploadResults;
+    }
+
+    public static FileInfo getFile(String groupName, String remoteFileName) {
+        try {
+            StorageClient storageClient = getTrackerClient();
+            return storageClient.get_file_info(groupName, remoteFileName);
+        } catch (IOException e) {
+            logger.error("IO Exception: Get File from Fast DFS failed", e);
+        } catch (Exception e) {
+            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
+        }
+        return null;
+    }
+
+    public static InputStream downFile(String groupName, String remoteFileName) {
+        try {
+            StorageClient storageClient = getTrackerClient();
+            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
+            InputStream ins = new ByteArrayInputStream(fileByte);
+            return ins;
+        } catch (IOException e) {
+            logger.error("IO Exception: Get File from Fast DFS failed", e);
+        } catch (Exception e) {
+            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
+        }
+        return null;
+    }
+
+    public static void deleteFile(String groupName, String remoteFileName)
+            throws Exception {
+        StorageClient storageClient = getTrackerClient();
+        int i = storageClient.delete_file(groupName, remoteFileName);
+        logger.info("delete file successfully!!!" + i);
+    }
+
+    public static StorageServer[] getStoreStorages(String groupName)
+            throws IOException {
+        TrackerClient trackerClient = new TrackerClient();
+        TrackerServer trackerServer = trackerClient.getConnection();
+        return trackerClient.getStoreStorages(trackerServer, groupName);
+    }
+
+    public static ServerInfo[] getFetchStorages(String groupName,
+                                                String remoteFileName) throws IOException {
+        TrackerClient trackerClient = new TrackerClient();
+        TrackerServer trackerServer = trackerClient.getConnection();
+        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
+    }
+
+    public static String getTrackerUrl() throws IOException {
+        return "http://" + getTrackerServer().getInetSocketAddress().getHostString() + ":" + ClientGlobal.getG_tracker_http_port() + "/";
+    }
+
+    private static StorageClient getTrackerClient() throws IOException {
+        TrackerServer trackerServer = getTrackerServer();
+        StorageClient storageClient = new StorageClient(trackerServer, null);
+        return storageClient;
+    }
+
+    private static TrackerServer getTrackerServer() throws IOException {
+        TrackerClient trackerClient = new TrackerClient();
+        TrackerServer trackerServer = trackerClient.getConnection();
+        return trackerServer;
+    }
+}

+ 70 - 0
prec-service/src/main/java/com/diagbot/client/fastdfs/FastDFSFile.java

@@ -0,0 +1,70 @@
+package com.diagbot.client.fastdfs;
+
+public class FastDFSFile {
+    private String name;
+
+    private byte[] content;
+
+    private String ext;
+
+    private String md5;
+
+    private String author;
+
+    public FastDFSFile(String name, byte[] content, String ext, String height,
+                       String width, String author) {
+        super();
+        this.name = name;
+        this.content = content;
+        this.ext = ext;
+        this.author = author;
+    }
+
+    public FastDFSFile(String name, byte[] content, String ext) {
+        super();
+        this.name = name;
+        this.content = content;
+        this.ext = ext;
+
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public byte[] getContent() {
+        return content;
+    }
+
+    public void setContent(byte[] content) {
+        this.content = content;
+    }
+
+    public String getExt() {
+        return ext;
+    }
+
+    public void setExt(String ext) {
+        this.ext = ext;
+    }
+
+    public String getMd5() {
+        return md5;
+    }
+
+    public void setMd5(String md5) {
+        this.md5 = md5;
+    }
+
+    public String getAuthor() {
+        return author;
+    }
+
+    public void setAuthor(String author) {
+        this.author = author;
+    }
+}

+ 49 - 0
prec-service/src/main/java/com/diagbot/config/FastDFSConfigurer.java

@@ -0,0 +1,49 @@
+package com.diagbot.config;
+
+import lombok.extern.slf4j.Slf4j;
+import org.csource.fastdfs.ClientGlobal;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.util.Properties;
+
+/**
+ * @Description:
+ * @author: gaodm
+ * @time: 2019/3/1 14:15
+ */
+@Configuration
+@Slf4j
+public class FastDFSConfigurer {
+    @Value("${fastdfs.connect_timeout_in_seconds}")
+    private String connectTimeout;
+    @Value("${fastdfs.network_timeout_in_seconds}")
+    private String networkTimeout;
+    @Value("${fastdfs.charset}")
+    private String charset;
+    @Value("${fastdfs.http_tracker_http_port}")
+    private String httpTrackerHttpPort;
+    @Value("${fastdfs.http_anti_steal_token}")
+    private String httpAntiStealToken;
+    @Value("${fastdfs.tracker_servers}")
+    private String trackerServers;
+
+    @Bean
+    public Integer fastDFSInit(){
+        try {
+            Properties props = new Properties();
+            props.put(ClientGlobal.PROP_KEY_CONNECT_TIMEOUT_IN_SECONDS, connectTimeout);
+            props.put(ClientGlobal.PROP_KEY_NETWORK_TIMEOUT_IN_SECONDS, networkTimeout);
+            props.put(ClientGlobal.PROP_KEY_CHARSET, charset);
+            props.put(ClientGlobal.PROP_KEY_HTTP_TRACKER_HTTP_PORT, httpTrackerHttpPort);
+            props.put(ClientGlobal.PROP_KEY_HTTP_ANTI_STEAL_TOKEN, httpAntiStealToken);
+            props.put(ClientGlobal.PROP_KEY_TRACKER_SERVERS, trackerServers);
+            ClientGlobal.initByProperties(props);
+
+        } catch (Exception e) {
+            log.error("FastDFS Client Init Fail!", e);
+        }
+        return 1;
+    }
+}

+ 27 - 0
prec-service/src/main/java/com/diagbot/dto/FileDTO.java

@@ -0,0 +1,27 @@
+package com.diagbot.dto;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * @Description:
+ * @Author:zhaops
+ * @time: 2018/12/18 17:08
+ */
+@Getter
+@Setter
+public class FileDTO {
+    private String state;
+    private String original;
+    private String title;
+    private String url;
+    private String info;
+
+    public FileDTO(String state, String info) {
+        this.state = state;
+        this.info = info;
+    }
+    public FileDTO(){
+
+    }
+}

+ 13 - 0
prec-service/src/main/java/com/diagbot/facade/UploadFacade.java

@@ -0,0 +1,13 @@
+package com.diagbot.facade;
+
+import com.diagbot.service.impl.UploadServiceImpl;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Description: 文件上传装饰层
+ * @author: gaodm
+ * @time: 2018/11/13 13:19
+ */
+@Component
+public class UploadFacade extends UploadServiceImpl {
+}

+ 13 - 0
prec-service/src/main/java/com/diagbot/service/UploadService.java

@@ -0,0 +1,13 @@
+package com.diagbot.service;
+
+import com.diagbot.dto.FileDTO;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * @Description: 文件上传服务接口
+ * @author: gaodm
+ * @time: 2018/11/13 13:50
+ */
+public interface UploadService {
+    FileDTO singleFileUpload(MultipartFile file);
+}

+ 98 - 0
prec-service/src/main/java/com/diagbot/service/impl/UploadServiceImpl.java

@@ -0,0 +1,98 @@
+package com.diagbot.service.impl;
+
+import com.diagbot.client.fastdfs.FastDFSClient;
+import com.diagbot.client.fastdfs.FastDFSFile;
+import com.diagbot.dto.FileDTO;
+import com.diagbot.service.UploadService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * @Description: 文件上传服务接口实现
+ * @author: gaodm
+ * @time: 2018/11/13 13:50
+ */
+@Slf4j
+@Service
+public class UploadServiceImpl implements UploadService {
+    @Override
+    public FileDTO singleFileUpload(MultipartFile file) {
+        if (file.isEmpty()) {
+            return new FileDTO("FAILURE", "文件不能为空");
+        }
+        //文件大小上限1M
+        if (file.getSize() > 1024 * 1024) {
+            return new FileDTO("FAILURE", "文件上传失败,超出大小限制1MB");
+        }
+        try {
+            FileDTO fileDTO = saveFile(file);
+            return fileDTO;
+        } catch (Exception e) {
+            log.error("文件上传失败", e);
+            return new FileDTO("FAILURE", "文件上传失败,请重新上传");
+        }
+    }
+
+
+    /**
+     * @param multipartFile
+     * @return
+     * @throws IOException
+     */
+    public FileDTO saveFile(MultipartFile multipartFile) throws IOException {
+
+        String[] fileAbsolutePath = {};
+        String fileName = multipartFile.getOriginalFilename();
+        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
+        byte[] file_buff = null;
+        InputStream inputStream = multipartFile.getInputStream();
+        if (inputStream != null) {
+            int len1 = inputStream.available();
+            file_buff = new byte[len1];
+            inputStream.read(file_buff);
+        }
+        inputStream.close();
+        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
+        try {
+            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
+        } catch (Exception e) {
+            log.error("文件上传异常", e);
+            return new FileDTO("FAILURE", "文件上传异常");
+        }
+        if (fileAbsolutePath == null) {
+            log.error("文件上传失败,请重新上传");
+            return new FileDTO("FAILURE", "文件上传失败,请重新上传");
+        }
+        String path = "/" + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
+        FileDTO fileDTO = new FileDTO("SUCCESS", "文件上传成功");
+        fileDTO.setUrl(path);
+        fileDTO.setOriginal(multipartFile.getOriginalFilename());
+        fileDTO.setTitle(multipartFile.getOriginalFilename());
+        return fileDTO;
+    }
+
+    /**
+     * 删除服务端文件
+     *
+     * @param path
+     * @return
+     */
+    public FileDTO deleteRemoteFile(String path) {
+        if (path.startsWith("/")) {
+            path = path.substring(1);
+        }
+        String fileName = path.substring(path.indexOf("/") + 1);
+        String groupName = path.substring(0, path.indexOf("/"));
+        try {
+            FastDFSClient.deleteFile(groupName, fileName);
+        } catch (Exception e) {
+            log.error("", e);
+            return new FileDTO("FAILURE", "文件删除失败");
+        }
+        return new FileDTO("SUCCESS", "文件删除成功");
+    }
+}

+ 51 - 0
prec-service/src/main/java/com/diagbot/web/UploadController.java

@@ -0,0 +1,51 @@
+package com.diagbot.web;
+
+import com.diagbot.dto.FileDTO;
+import com.diagbot.facade.UploadFacade;
+import com.diagbot.util.FastJsonUtils;
+import com.diagbot.util.StringUtil;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@RestController
+@Api(value = "文件上传API", tags = { "文件上传API" })
+@RequestMapping(value = "/file")
+@SuppressWarnings("unchecked")
+public class UploadController {
+    @Autowired
+    private UploadFacade uploadFacade;
+
+    @ApiOperation(value = "文件上传")
+    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*", methods = { RequestMethod.POST }, origins = "*")
+    @PostMapping(value = "/uploadImage", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
+    public String singleFileUpload(@RequestParam("upfile") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
+        FileDTO fileDTO = uploadFacade.singleFileUpload(file);
+        String data = FastJsonUtils.getBeanToJson(fileDTO);
+        response.setContentType("text/plain;charset=UTF-8");
+
+        String callback = request.getParameter("callback");//客户端请求参数
+        if (callback != null && StringUtil.isNotBlank(callback)) {
+            data = callback + "(" + data + ")";
+        }
+        return data;
+    }
+
+    @PostMapping("/deleteRemoteFile")
+    @ApiOperation(value = "知识库标准化-文件删除")
+    public String deleteRemoteFile(@RequestParam("path") String path) {
+        String data = FastJsonUtils.getBeanToJson(uploadFacade.deleteRemoteFile(path));
+        return data;
+    }
+}