Browse Source

FastFDS上传接口编写

gaodm 6 năm trước cách đây
mục cha
commit
367953b637

+ 1 - 1
diagbotman-service/src/main/java/com/diagbot/aop/SysLoggerExprotAspect.java

@@ -68,7 +68,7 @@ public class SysLoggerExprotAspect {
             sysLog.setUsername(username);
         }
         sysLog.setGmtCreate(new Date());
-        sysLog.setSysType(SysTypeEnum.USER_SERVICE.getKey());
+        sysLog.setSysType(SysTypeEnum.DIAGBOTMAN_SERVICE.getKey());
         //保存系统日志
         mySender.outputLogSend(sysLog);
     }

+ 6 - 0
icssman-service/pom.xml

@@ -149,6 +149,12 @@
             <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>
+
     </dependencies>
 
     <build>

+ 126 - 0
icssman-service/src/main/java/com/diagbot/client/fastdfs/FastDFSClient.java

@@ -0,0 +1,126 @@
+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 org.springframework.core.io.ClassPathResource;
+
+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);
+
+	static {
+		try {
+			String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
+			ClientGlobal.init(filePath);
+		} catch (Exception e) {
+			logger.error("FastDFS Client Init Fail!",e);
+		}
+	}
+
+	public static String[] upload(FastDFSFile file) {
+		logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
+
+		NameValuePair[] meta_list = new NameValuePair[1];
+		meta_list[0] = 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
icssman-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;
+	}
+}

+ 1 - 0
icssman-service/src/main/java/com/diagbot/config/ResourceServerConfigurer.java

@@ -26,6 +26,7 @@ public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
                 .csrf().disable()
                 .authorizeRequests()
                 .regexMatchers(".*swagger.*", ".*v2.*", ".*webjars.*", "/druid.*", "/actuator.*", "/hystrix.*").permitAll()
+                .antMatchers("/file/upload").permitAll()
                 .antMatchers("/**").authenticated();
         //        .antMatchers("/**").permitAll();
     }

+ 1 - 0
icssman-service/src/main/java/com/diagbot/config/security/UrlAccessDecisionManager.java

@@ -89,6 +89,7 @@ public class UrlAccessDecisionManager implements AccessDecisionManager {
                 || matchers("/druid/**", request)
                 || matchers("/actuator/**", request)
                 || matchers("/hystrix/**", request)
+                || matchers("/file/upload", request)
                 || matchers("/", request)) {
             return true;
         }

+ 39 - 0
icssman-service/src/main/java/com/diagbot/exception/ServiceErrorCode.java

@@ -0,0 +1,39 @@
+package com.diagbot.exception;
+
+/**
+ * @Description: 本服务错误码
+ * 系统码(3位) + 等级码(1位) + 4位顺序号
+ * 系统码 通用码 000;用户中心 100; 管理中心 200;
+ * @author: gaodm
+ * @time: 2018/9/10 11:11
+ */
+public enum ServiceErrorCode implements ErrorCode {
+    FILE_UPLOAD_ERROE("12020001", "文件上传出错");
+
+    private String code;
+    private String msg;
+
+
+    ServiceErrorCode(String code, String msg) {
+        this.code = code;
+        this.msg = msg;
+    }
+
+
+    public String getCode() {
+        return code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public static ServiceErrorCode codeOf(String code) {
+        for (ServiceErrorCode state : values()) {
+            if (state.getCode() == code) {
+                return state;
+            }
+        }
+        return null;
+    }
+}

+ 13 - 0
icssman-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 {
+}

+ 12 - 0
icssman-service/src/main/java/com/diagbot/service/UploadService.java

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

+ 71 - 0
icssman-service/src/main/java/com/diagbot/service/impl/UploadServiceImpl.java

@@ -0,0 +1,71 @@
+package com.diagbot.service.impl;
+
+import com.diagbot.client.fastdfs.FastDFSClient;
+import com.diagbot.client.fastdfs.FastDFSFile;
+import com.diagbot.exception.CommonException;
+import com.diagbot.exception.ServiceErrorCode;
+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 String singleFileUpload(MultipartFile file) {
+        String path = "";
+        if (file.isEmpty()) {
+            throw new CommonException(ServiceErrorCode.FILE_UPLOAD_ERROE, "文件不能为空");
+        }
+        try {
+            // Get the file and save it somewhere
+            path = saveFile(file);
+        } catch (Exception e) {
+            log.error("upload file failed", e);
+            throw new CommonException(ServiceErrorCode.FILE_UPLOAD_ERROE, "upload file failed");
+        }
+        return path;
+    }
+
+    /**
+     * @param multipartFile
+     * @return
+     * @throws IOException
+     */
+    public String 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("upload file Exception!", e);
+            throw new CommonException(ServiceErrorCode.FILE_UPLOAD_ERROE, "upload file Exception");
+        }
+        if (fileAbsolutePath == null) {
+            log.error("upload file failed,please upload again!");
+            throw new CommonException(ServiceErrorCode.FILE_UPLOAD_ERROE, "upload file failed,please upload again");
+        }
+        String path = "/" + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
+        return path;
+
+    }
+}

+ 25 - 0
icssman-service/src/main/java/com/diagbot/web/UploadController.java

@@ -0,0 +1,25 @@
+package com.diagbot.web;
+
+import com.diagbot.dto.RespDTO;
+import com.diagbot.facade.UploadFacade;
+import io.swagger.annotations.Api;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+@RestController
+@Api(value = "文件上传API", tags = { "文件上传API" })
+@RequestMapping("/file")
+@SuppressWarnings("unchecked")
+public class UploadController {
+    @Autowired
+    private UploadFacade uploadFacade;
+
+    @PostMapping("/upload")
+    public RespDTO<String> singleFileUpload(@RequestParam("file") MultipartFile file) {
+        return RespDTO.onSuc(uploadFacade.singleFileUpload(file));
+    }
+}

+ 7 - 0
icssman-service/src/main/resources/fdfs_client.conf

@@ -0,0 +1,7 @@
+connect_timeout = 60
+network_timeout = 60
+charset = UTF-8
+http.tracker_http_port = 8080
+http.anti_steal_token = no
+
+tracker_server = 192.168.2.236:22122