Browse Source

【功能完善】【上传附件同时上传FTP服务器】

koul 5 days ago
parent
commit
d17a0ed757

+ 10 - 1
pom.xml

@@ -118,7 +118,16 @@
 		    <artifactId>flexjson</artifactId>
 		    <version>2.1</version>
 		</dependency>
-		
+		<dependency>
+			<groupId>com.jcraft</groupId>
+			<artifactId>jsch</artifactId>
+			<version>0.1.53</version>
+		</dependency>
+		<dependency>
+			<groupId>commons-net</groupId>
+			<artifactId>commons-net</artifactId>
+			<version>3.6</version>
+		</dependency>
 		<dependency>
 		    <groupId>org.springframework.boot</groupId>
 		    <artifactId>spring-boot-starter-cache</artifactId>

+ 54 - 0
src/main/java/com/uas/eis/entity/FTPConfig.java

@@ -0,0 +1,54 @@
+package com.uas.eis.entity;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Component
+@ConfigurationProperties(prefix = "ftp")
+public class FTPConfig {
+	private String host;
+	private int port;
+	private String username;
+	private String password;
+	private String folder;
+
+	public String getHost() {
+		return host;
+	}
+
+	public void setHost(String host) {
+		this.host = host;
+	}
+
+	public int getPort() {
+		return port;
+	}
+
+	public void setPort(int port) {
+		this.port = port;
+	}
+
+	public String getUsername() {
+		return username;
+	}
+
+	public void setUsername(String username) {
+		this.username = username;
+	}
+
+	public String getPassword() {
+		return password;
+	}
+
+	public void setPassword(String password) {
+		this.password = password;
+	}
+
+	public String getFolder() {
+		return folder;
+	}
+
+	public void setFolder(String folder) {
+		this.folder = folder;
+	}
+}

+ 42 - 0
src/main/java/com/uas/eis/serviceImpl/MESDataServiceImpl.java

@@ -4,6 +4,7 @@ import com.uas.eis.core.config.SpObserver;
 import com.uas.eis.dao.BaseDao;
 import com.uas.eis.dao.SqlRowList;
 import com.uas.eis.entity.ErrorMessage;
+import com.uas.eis.entity.FTPConfig;
 import com.uas.eis.exception.ApiSystemException;
 import com.uas.eis.sdk.entity.ApiResult;
 import com.uas.eis.sdk.resp.ApiResponse;
@@ -16,6 +17,7 @@ import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.multipart.MultipartFile;
+import org.apache.commons.net.ftp.FTPClient;
 
 import java.io.File;
 import java.io.IOException;
@@ -31,6 +33,9 @@ public class MESDataServiceImpl implements MESDataService {
 	@Value("${spring.datasource.username}")
 	private String username;
 
+	@Autowired
+	private FTPConfig ftpConfig;
+
 	@Override
 	public List<Map<Object,Object>> snStepPass(String accessKey, String requestId, String data) {
 		String AE_MASTER = checkAccessKey(accessKey, requestId);
@@ -393,6 +398,8 @@ public class MESDataServiceImpl implements MESDataService {
 		try {
 			String filename = file.getOriginalFilename();
 			String path = saveFile(file);
+			//上传FTP
+			uploadFTP(convertMultiPartFileToFile(file));
 			int id = saveFilePath(accessKey, requestId,path, (int) file.getSize(), filename,data);
 			return ApiResponse.successRsp("0", "Success", requestId, "");
 		}catch (Exception e) {
@@ -529,4 +536,39 @@ public class MESDataServiceImpl implements MESDataService {
 		return AE_MASTER.toString();
 	}
 
+	private void uploadFTP(File file){
+		Map<String,Object> map=new HashMap<String,Object>();
+		String folder = ftpConfig.getFolder();
+		map.put("ip", ftpConfig.getHost());
+		map.put("port", ftpConfig.getPort());
+		map.put("user", ftpConfig.getUsername());
+		map.put("password", ftpConfig.getPassword());
+		FTPClient connect = FtpUtil.connect(map, folder);
+		if (connect != null){
+			FtpUtil.uploadFile(connect, folder,file);
+		}
+
+	}
+
+	private File convertMultiPartFileToFile(MultipartFile multipartFile) throws IOException {
+		// 使用系统临时目录,并生成唯一文件名
+		String fileName = multipartFile.getOriginalFilename();
+		// 为了防止文件名冲突,可以添加随机前缀或使用UUID
+		String prefix = UUID.randomUUID().toString();
+		File file = File.createTempFile(prefix, getFileExtension(fileName));
+		multipartFile.transferTo(file);
+		return file;
+	}
+
+	private String getFileExtension(String fileName) {
+		if (fileName == null) {
+			return "";
+		}
+		int lastIndex = fileName.lastIndexOf('.');
+		if (lastIndex == -1) {
+			return "";
+		}
+		return fileName.substring(lastIndex);
+	}
+
 }

+ 312 - 0
src/main/java/com/uas/eis/utils/FtpUtil.java

@@ -0,0 +1,312 @@
+package com.uas.eis.utils;
+
+import com.jcraft.jsch.JSchException;
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.net.ftp.FTPFile;
+import org.apache.commons.net.ftp.FTPReply;
+
+import java.io.*;
+import java.util.*;
+
+public class FtpUtil {
+	/**
+	 * 连接到ftp站点,判断是否可以连接
+	 * @param path  要连接到的目录
+	 * @param addr  站点地址
+	 * @param port  端口
+	 * @param username 用户名
+	 * @param password 密码
+	 * @return
+	 * @throws Exception
+	 */
+	public static boolean connect(String path, String addr, int port, String username,
+			String password) {
+		boolean result = false;
+		try {
+			FTPClient ftp = new FTPClient();
+			int reply;
+			ftp.connect(addr, port);
+			ftp.login(username, password);
+			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
+			reply = ftp.getReplyCode();
+			if (!FTPReply.isPositiveCompletion(reply)) {
+				ftp.disconnect();
+				return result;
+			}
+			ftp.changeWorkingDirectory(path);
+			result = true;
+			return result;
+		}catch (Exception e){
+			e.printStackTrace();
+			return result;
+		}
+	}
+	
+	/**
+	 * 获取ftp连接,该连接指向ftp配置中的downloadpath文件夹
+	 * @param map 包含ftp连接配置的map
+	 */
+	public static FTPClient connect(Map<String,Object> map) throws Exception {
+		return connect(map,map.get("downloadpath").toString());
+	}
+
+	/**
+	 * 获取ftp连接,该连接指向ftp配置中的downloadpath文件夹
+	 * @param map 包含ftp连接配置的map
+	 */
+	public static FTPClient connect(Map<String,Object> map,String path){
+		FTPClient ftp = null;
+		String addr = null;
+		try{
+			addr = map.get("ip").toString();
+			int port = Integer.parseInt(map.get("port").toString());
+			String username = map.get("user").toString();
+			String password = map.get("password").toString();
+			ftp = new FTPClient();
+			int reply;
+			ftp.setDefaultTimeout(30*1000);
+			ftp.setConnectTimeout(30*1000);
+			ftp.setDataTimeout(30*1000);
+			//设置ftp为被动模式,解决有时候ftp会卡住问题
+			ftp.enterLocalPassiveMode();
+			ftp.connect(addr, port);
+			if(!ftp.login(username, password)){
+				return null;
+			}
+			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
+			reply = ftp.getReplyCode();
+			if (!FTPReply.isPositiveCompletion(reply)) {
+				ftp.disconnect();
+				return null;
+			}
+			ftp.changeWorkingDirectory(path);
+			return ftp;			
+		}catch(Exception e){
+			e.printStackTrace();
+			return null;
+		}
+	}
+
+	/**
+	 * 上传文件
+	 * @param ftpClient 已连接的ftp客户端
+	 * @param pathname 路径
+	 * @param file 待上传的文件
+	 * @return 上传结果
+	 */
+	public static boolean uploadFile(FTPClient ftpClient, String pathname, File file) {
+		boolean flag = false;
+		ftpClient.setControlEncoding("UTF-8");
+		try {
+			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
+			boolean change = ftpClient.changeWorkingDirectory("/"+pathname);
+			if(!change){
+				return false;
+			}
+			InputStream inputStream = new FileInputStream(file);
+			ftpClient.enterLocalPassiveMode();
+			ftpClient.storeFile(file.getName(), inputStream);
+			inputStream.close();
+			//ftpClient.logout();
+			flag = true;
+		} catch (Exception e) {
+			e.printStackTrace();
+			if (ftpClient.isConnected()) {
+				try {
+					ftpClient.disconnect();
+				} catch (IOException e1) {
+					e1.printStackTrace();
+				}
+			}
+		}
+		return flag;
+	}
+	
+	/**
+	 * 删除后关闭ftp连接
+	 * @param ftpClient 
+	 * @param filename 要删除的文件名
+	 * @return 删除结果
+	 */
+	public static boolean deleteFile(FTPClient ftpClient,String filename) {
+		boolean flag = false;
+		try {
+			ftpClient.dele(filename);
+			flag = true;
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return flag;
+	}
+
+	/**
+	 * 
+	 * @param ftpClient
+	 * fileType 需要下载的文件类型
+	 * @return 获取连接到的ftp站点下的文件夹所有文件
+	 */
+	public static List<File> downloadAllFileByType(FTPClient ftpClient,String fileType) {
+		List<File> files = new ArrayList<File>();	
+		try {
+			ftpClient.enterLocalPassiveMode();
+			FTPFile[] ftpFiles = ftpClient.listFiles();
+			if (ftpFiles != null && ftpFiles.length > 0) {
+				ArrayList<FTPFile> list = new ArrayList<FTPFile>(Arrays.asList(ftpFiles));
+				Collections.sort(list, new Comparator<FTPFile>() {
+					@Override
+					public int compare(FTPFile o1, FTPFile o2) {
+						long time = o1.getTimestamp().getTime().getTime();
+						long time1 = o2.getTimestamp().getTime().getTime();
+						if (time > time1) {
+							return 1;
+						}
+						if (time == time1) {
+							return 0;
+						}
+						return -1;
+					}
+				});
+				for (FTPFile file : list) {
+					if (file.getName().toUpperCase().endsWith("." + fileType)) {
+						File localFile = new File(System.getProperty("java.io.tmpdir") + File.separator + file.getName());
+						OutputStream os = new FileOutputStream(localFile);
+						ftpClient.retrieveFile(file.getName(), os);
+						os.close();
+						files.add(localFile);
+					}
+				}
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return files;
+	}
+
+	/**
+	 *
+	 * @param ftpClient
+	 * fileType 需要下载的文件类型
+	 * @return 获取连接到的ftp站点下的文件夹所有文件
+	 */
+	public static List<File> downloadAllFileByType(FTPClient ftpClient) {
+		List<File> files = new ArrayList<File>();
+		try {
+			ftpClient.enterLocalPassiveMode();
+			FTPFile[] ftpFiles = ftpClient.listFiles();
+			for (FTPFile file : ftpFiles) {
+				if(!".".equals(file.getName()) && !"..".equals(file.getName())&& !"bak".equals(file.getName())){
+					File localFile = new File(System.getProperty("java.io.tmpdir") + File.separator + file.getName());
+					OutputStream os = new FileOutputStream(localFile);
+					ftpClient.retrieveFile(file.getName(), os);
+					os.close();
+					files.add(localFile);
+				}
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return files;
+	}
+
+	/**
+	 * 关闭ftp连接
+	 * @param ftpClient
+	 */
+	public static void closeFtpClient(FTPClient ftpClient){
+		if (ftpClient.isConnected()) {
+			try {
+				ftpClient.logout();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}		
+	}
+
+
+	/**
+ *
+ * @param ftpClient
+ * @return 获取连接到的ftp站点下的文件夹所有文件
+ */
+public static List<File> downloadFileByDirectory(FTPClient ftpClient,String directory,String fileType) {
+	List<File> files = new ArrayList<File>();
+	try {
+		ftpClient.enterLocalPassiveMode();
+		ftpClient.changeWorkingDirectory("/" + directory);// 转移到FTP服务器目录
+		FTPFile[] ftpFiles = ftpClient.listFiles();
+		if (ftpFiles != null && ftpFiles.length > 0) {
+			ArrayList<FTPFile> list = new ArrayList<FTPFile>(Arrays.asList(ftpFiles));
+			Collections.sort(list, new Comparator<FTPFile>() {
+				@Override
+				public int compare(FTPFile o1, FTPFile o2) {
+					long time = o1.getTimestamp().getTime().getTime();
+					long time1 = o2.getTimestamp().getTime().getTime();
+					if (time > time1) {
+						return 1;
+					}
+					if (time == time1) {
+						return 0;
+					}
+					return -1;
+				}
+			});
+			for (FTPFile file : list) {
+				if (file.getName().toUpperCase().endsWith("." + fileType)) {
+					File localFile = new File(System.getProperty("java.io.tmpdir") + File.separator + file.getName());
+					OutputStream os = new FileOutputStream(localFile);
+					ftpClient.retrieveFile(file.getName(), os);
+					os.close();
+					files.add(localFile);
+				}
+			}
+		}
+	} catch (Exception e) {
+		e.printStackTrace();
+	}
+	return files;
+}
+
+	/**
+	 *
+	 * @param ftpClient
+	 * @return 获取连接到的ftp站点下的文件夹所有文件
+	 */
+	public static List<File> downloadFileByDirectory(FTPClient ftpClient,String directory) {
+		List<File> files = new ArrayList<File>();
+		try {
+			ftpClient.enterLocalPassiveMode();
+			// 转移到FTP服务器目录
+			ftpClient.changeWorkingDirectory("/" + directory);
+			FTPFile[] ftpFiles = ftpClient.listFiles();
+			if (ftpFiles != null && ftpFiles.length > 0) {
+				ArrayList<FTPFile> list = new ArrayList<FTPFile>(Arrays.asList(ftpFiles));
+				Collections.sort(list, new Comparator<FTPFile>() {
+					@Override
+					public int compare(FTPFile o1, FTPFile o2) {
+						long time = o1.getTimestamp().getTime().getTime();
+						long time1 = o2.getTimestamp().getTime().getTime();
+						if (time > time1) {
+							return 1;
+						}
+						if (time == time1) {
+							return 0;
+						}
+						return -1;
+					}
+				});
+				for (FTPFile file : list) {
+					if(!".".equals(file.getName()) && !"..".equals(file.getName())&& !"bak".equals(file.getName())&& !"failed".equals(file.getName())) {
+						File localFile = new File(System.getProperty("java.io.tmpdir") + File.separator + file.getName());
+						OutputStream os = new FileOutputStream(localFile);
+						ftpClient.retrieveFile(file.getName(), os);
+						os.close();
+						files.add(localFile);
+					}
+				}
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return files;
+	}
+}

+ 6 - 0
src/main/resources/application.yml

@@ -39,3 +39,9 @@ extral:
         uid: admin1
         pwd: 123456789
         lang: 2052
+ftp:
+    host: 10.1.6.206
+    port: 21
+    username: HUAWE1
+    password: lvquanming
+    folder: /1