【沫沫金】使用Serv-U FTP服务,搭建文件服务器

内网文件服务器安装Serv-U FTP

链接: https://pan.baidu.com/s/1G51D1enLqZCUhnprnjAITw 提取码: snah

Java Web工程,引入

commons-net.jar

拷贝工具类

package com.ytsoft.appservice.framework.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ftp工具类,基于org.apache.commons.net.ftp
 */
public class FtpUtilCommons {

	private final static Logger logger = LoggerFactory.getLogger(FtpUtilCommons.class);

	private FTPClient ftpClient;
	private String ipAddr;// ip地址
	private Integer port;// 端口号
	private String userName;// 用户名
	private String pwd;// 密码
	private String path;// 根目录
	private String ysPath; // 原始目录
	private String lsPath; // 历史目录
	private String logPath; // log目录

	public FtpUtilCommons(String ipAddr, Integer port, String userName, String pwd) {
		this.ipAddr = ipAddr;
		this.port = port;
		this.userName = userName;
		this.pwd = pwd;
	}

	/**
	 * 本地字符编码
	 */
	private static String LOCAL_CHARSET = "GBK";

	// FTP协议里面,规定文件名编码为iso-8859-1
	private static String SERVER_CHARSET = "ISO-8859-1";

	/**
	 * 获取ftp连接
	 *
	 * @param ftpVo
	 * @return
	 * @throws Exception
	 */
	public boolean connectFtp() throws Exception {
		logger.info("获取ftp连接,username---" + this.userName);
		boolean flag = false;
		try {
			ftpClient = new FTPClient();
			ftpClient.setDataTimeout(18000 * 1000);
			int reply;
			if (this.getPort() == null) {
				ftpClient.connect(this.getIpAddr(), 21);
			} else {
				ftpClient.connect(this.getIpAddr(), this.getPort());
			}
			if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				if (ftpClient.login(this.getUserName(), this.getPwd())) {
					// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
					if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
						LOCAL_CHARSET = "UTF-8";
					}
					ftpClient.setControlEncoding(LOCAL_CHARSET);
					ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
					reply = ftpClient.getReplyCode();
					if (!FTPReply.isPositiveCompletion(reply)) {
						ftpClient.disconnect();
						logger.error("连接ftp失败,reply=" + reply);
						return flag;
					}
					ftpClient.enterLocalPassiveMode();
					Boolean boo = ftpClient.changeWorkingDirectory(this.getPath());
					logger.info("获取ftp连接,切换的目录是否存在:" + boo + ",当前目录:" + getPath());
					flag = true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUserName() + ",连接ftp异常,e=" + e.getMessage());

		}
		return flag;
	}

	/**
	 * 得到文件名称列表
	 *
	 * @return
	 */
	public String[] getFileNameList() {
		String[] fileNames = null;
		try {
			ftpClient.setControlEncoding(LOCAL_CHARSET);
			fileNames = ftpClient.listNames();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("得到文件名称列表异常,e=" + e.getMessage());
		}
		return fileNames;
	}

	/**
	 * 移动文件
	 *
	 * @param oldFileName
	 * @param newFileName
	 * @return
	 */
	public boolean rename(String oldFileName, String newFileName) throws Exception {
		boolean flag = false;
		try {
			logger.info("ftp文件移动,oldFileName=" + oldFileName + ";newFileName=" + newFileName);
			oldFileName = new String(oldFileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
			newFileName = new String(newFileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
			ftpClient.enterLocalPassiveMode();
			flag = ftpClient.rename(oldFileName, newFileName);
			logger.info("ftp文件移动结果," + flag);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
			logger.error("ftp文件移动异常,从新连接FTP,e=" + e.getMessage());
			connectFtp();

		}
		return flag;
	}

	/**
	 * 关闭ftp连接
	 */
	public void closeFtp() {
		logger.info("ftp关闭-start");
		if (ftpClient != null && ftpClient.isConnected()) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				logger.error("关闭ftp失败,e=" + e.getMessage());
			}
		}
		logger.info("ftp关闭-end");
	}

	/**
	 * ftp上传文件,针对数据采集自动化,上传错误日志
	 *
	 * @param file
	 * @param path
	 *            目录
	 * @throws Exception
	 */
	public String upload(File file, String path) throws Exception {
		FileInputStream fis = null;
		try {
			boolean boo = ftpClient.changeWorkingDirectory(path);
			logger.info("ftp上传文件,切换到log目录,boo=" + boo + ";Path:" + getPath());
			logger.info("ftp上传文件,f===" + file.toString());
			if (!file.exists()) {
				return "文件不存在!";
			}
			File file2 = new File(file.getPath());
			fis = new FileInputStream(file2);
			ftpClient.enterLocalPassiveMode();
			boolean boolen = ftpClient.storeFile(new String(file2.getName().getBytes(LOCAL_CHARSET), SERVER_CHARSET), fis);
			logger.info("ftp上传文件,上传结果boolean=" + boolen);
			if (!boolen) {
				return "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUserName() + "上传文件发生异常,重新连接ftp,e=" + e.getMessage());
			connectFtp();
			return "error";
		} finally {
			if (fis != null) {
				fis.close();
			}
			ftpClient.changeWorkingDirectory("/YSSJ/");
		}
		logger.info("ftp上传文件完成");
		return "success";
	}

	/**
	 * 下载文件
	 *
	 * @param remoteFileName--服务器上的文件名
	 * @param localFileName--本地文件名
	 * @return true 下载成功,false 下载失败
	 */
	public boolean loadFile(String remoteFileName, String localFileName) throws Exception {
		boolean flag = false;
		// 下载文件
		BufferedOutputStream buffOut = null;
		try {
			buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
			flag = ftpClient.retrieveFile(new String(remoteFileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET), buffOut);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUserName() + "下载ftp文件异常,e=" + e.getMessage());
			flag = false;
			logger.error("下载ftp文件异常,重新连接一次FTP");
			connectFtp();

		} finally {
			try {
				if (buffOut != null)
					buffOut.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		logger.info("下载ftp文件结果,flag=" + flag);
		return flag;
	}

	/**
	 * 删除ftp指定文件
	 */
	public String deleteFile(String filename) {
		logger.info("删除ftp文件,filename=" + filename);
		try {
			ftpClient.deleteFile(filename);
			return null;
		} catch (Exception e) {
			logger.error("删除ftp文件异常,e=" + e.getMessage());
			return "删除文件失败!";
		}
	}

	/**
	 * 判断文件是否存在
	 *
	 * @param filename
	 * @return
	 */
	public Boolean getFileName(String filename) {
		logger.info("判断文件在ftp是否存在,filename=" + filename);
		try {
			ftpClient.enterLocalPassiveMode();
			FTPFile[] files = ftpClient.listFiles(filename);
			if (files.length < 1) {
				return false;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("判断文件在ftp是否存在,存在!");
		return true;
	}

	/**
	 * 获得当前连接目录
	 *
	 * @return
	 */
	public String getPath() {
		String path = null;
		try {
			path = ftpClient.printWorkingDirectory();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return path;
	}

	public static void main(String[] args) throws Exception {
		/*
		 * FtpUtilCommons ftpUtil = new FtpUtilCommons(); FtpVo f=new FtpVo();
		 * f.setIpAddr("10.5.94.11"); f.setUserName("01606034X");
		 * f.setPwd("610929"); f.setPath("LOG/"); ftpUtil.connectFtp(f);
		 * 
		 * 
		 * File file = new File(
		 * "D:\usr\wonders\JKK\sjcj\安康市白河县仓上镇(未办理身份证人员)258220161214-092640.log"
		 * ); ftpUtil.upload(file);//把文件上传在ftp上 System.out.println("ok");
		 * ftpUtil.closeFtp();
		 */

		FtpUtilCommons ftpUtil = new FtpUtilCommons("127.0.0.1", 21, "wyc", "123456");
		System.out.println(ftpUtil.connectFtp());
		String[] str = ftpUtil.getFileNameList();

		System.out.println(str.length);
		int i = 0;
		for (String s : str) {

			System.out.println(s);

		}
		// ftpUtil.upload(new
		// File("F:\ceshi\安康市白河县西营镇7496.xlsx安康市白河县西营镇7496.xlsx"));
		ftpUtil.closeFtp();
	}

	public String getIpAddr() {
		return ipAddr;
	}

	public void setIpAddr(String ipAddr) {
		this.ipAddr = ipAddr;
	}

	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getLsPath() {
		return lsPath;
	}

	public void setLsPath(String lsPath) {
		this.lsPath = lsPath;
	}

	public String getLogPath() {
		return logPath;
	}

	public void setLogPath(String logPath) {
		this.logPath = logPath;
	}

	public void setPath(String path) {
		this.path = path;
	}

}

下载

@GetMapping("/downloadFile/{fileName:.+}")
	public Object downloadFile(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		json.put("status", -1);
		try {
			// 如果文件名不为空,则进行下载
			if (fileName != null) {
				// 设置文件路径

				String address = environment.getProperty("ftp.address");
				String user = environment.getProperty("ftp.user");
				String password = environment.getProperty("ftp.password");

				String path = System.getProperty("java.io.tmpdir");
				FtpUtilCommons ftpUtil = new FtpUtilCommons(address, null, user, password);
				ftpUtil.connectFtp();
				ftpUtil.loadFile(fileName, path + fileName);
				ftpUtil.closeFtp();

				File file = new File(path + fileName);

				// 如果文件名存在,则进行下载
				if (file.exists()) {

					// 配置文件下载
					response.setHeader("content-type", "application/octet-stream");
					response.setContentType("application/octet-stream");
					// 下载文件能正常显示中文
					response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

					// 实现文件下载
					byte[] buffer = new byte[1024];
					FileInputStream fis = null;
					BufferedInputStream bis = null;
					try {
						fis = new FileInputStream(file);
						bis = new BufferedInputStream(fis);
						OutputStream os = response.getOutputStream();
						int i = bis.read(buffer);
						while (i != -1) {
							os.write(buffer, 0, i);
							i = bis.read(buffer);
						}
						json.put("status", 1);
						json.put("message", "文件下载成功");
						json.put("data", "");
					} catch (Exception e) {
						throw new Exception("文件下载失败!");
					} finally {
						if (bis != null) {
							try {
								bis.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						if (fis != null) {
							try {
								fis.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						file.delete();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("message", e.getMessage());
			return json;
		}
		return json;
	}

 上传

@PostMapping("/uploadFile")
	public Object uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
		JSONObject json = new JSONObject();
		json.put("status", -1);
		try {
			FileService fileService = new FileService();
			String filePath = fileService.storeFile(file);
			String address = environment.getProperty("ftp.address");
			String user = environment.getProperty("ftp.user");
			String password = environment.getProperty("ftp.password");

			String path = System.getProperty("java.io.tmpdir");
			String fileName = file.getOriginalFilename();
			String s = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			String newFileName = UUID.randomUUID().toString().replace("-", "") + s;
			File f = new File(path + newFileName);
			file.transferTo(f);

			FtpUtilCommons ftpUtil = new FtpUtilCommons(address, null, user, password);
			ftpUtil.connectFtp();
			ftpUtil.upload(f, "");
			ftpUtil.closeFtp();

			f.delete();

			UploadFileResponse uploadFileResponse = new UploadFileResponse(StringUtils.cleanPath(file.getOriginalFilename()), filePath, file.getContentType(), file.getSize());
			HashMap<String, Object> data = new HashMap<String, Object>();
			data.put("ID", "");
			data.put("SETID", req.getParameter("SETID"));
			data.put("FILENAME", newFileName);
			data.put("ATTACHEDFILE", uploadFileResponse.getFileDownloadUri());

			fileMapper mapper = firstSqlSessionFactory.getMapper(fileMapper.class);

			int i = mapper.insert(data);
			if (i == 1) {
				// 更新到故障表单
				ProblemFromMapper pfm = firstSqlSessionFactory.getMapper(ProblemFromMapper.class);
				HashMap<String, Object> updateFileMap = new HashMap<String, Object>();
				updateFileMap.put("ID", req.getParameter("ID"));
				updateFileMap.put("INCUSERATTACHMENT15", data.get("ID"));
				int j = pfm.updateFile(updateFileMap);

				json.put("status", 1);
				json.put("message", "文件上传成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("message", e.getMessage());
			return json;
		}
		return json;
	}

就可以了。

原文地址:https://www.cnblogs.com/zl0828/p/11586603.html