使用apache的FTPServer搭建ftp服务器

一:启动ftp服务html

1.下载Apache FtpServer 1.0.6 Releasehttp://mina.apache.org/downloads-ftpserver.htmljava

2.解压后res/conf下找到user.properties  (修改密码为admin默认是md5加密后的)web

3.到res/conf下配置tpd-typical.xml文件spring

<server xmlns="http://mina.apache.org/ftpserver/spring/v1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
	   http://mina.apache.org/ftpserver/spring/v1 http://mina.apache.org/ftpserver/ftpserver-1.0.xsd	
	   "
	id="myServer" anon-enabled="false" max-logins="100">
	<listeners>
		<nio-listener name="default" port="21">
		    <ssl>
                <keystore file="./res/ftpserver.jks" password="password" />
            </ssl>
		</nio-listener>
	</listeners>
	<file-user-manager file="./res/conf/users.properties" encrypt-passwords="clear"/>
</server>

4.到bin目录下:用下面命令启动ftp服务器 ftpd.bat res/conf/ftpd-typical.xmlapache

5.打开个人电脑输入 ftp://localhost:21/缓存

右击登陆,输入admin/admintomcat

二:java后台实现上传下载服务器

1.须要Apache Commons Net jar包引入pom.xmlapp

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.3</version>
</dependency>

2.FtpUtils.classwebapp

package com.test.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.text.SimpleDateFormat;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

public class FtpUtils {

	private final static Logger logger = Logger.getLogger(FtpUtils.class);
	private final static SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");

	private final static String USER_NAME = "admin"; // ftp登陆用户名
	private final static String USER_PASSWORD = "admin"; // ftp登陆密码
	private final static String SERVER_IP = "192.168.1.133";// 直接ip地址
	private final static int SERVER_PORT = 21;// 端口号

	private final static String WEB_URL = "localhost:8080";

	/**
	 * 获取ftp链接对象
	 * 
	 * @param parentDirName
	 * @return
	 * @throws FtpException
	 */
	public static FTPClient getFTPClient(String parentDirName) throws FtpException {
		FTPClient ftpClient = new FTPClient();
		try {
			// 链接服务器
			ftpClient.connect(SERVER_IP, SERVER_PORT);
			// 登录ftp
			ftpClient.login(USER_NAME, USER_PASSWORD);
			// 判断登录是否成功
			int reply = ftpClient.getReplyCode();

			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				logger.error("登录ftp失败");
				throw new FtpException("登录ftp失败");
			}
			boolean res = ftpClient.changeWorkingDirectory(parentDirName);
			if (!res) {
				ftpClient.disconnect();
				logger.error("文件夹不存在");
				throw new FtpException("文件夹不存在");
			}
			// 设置属性
			ftpClient.setBufferSize(1024);// 设置上传缓存大小
			ftpClient.setControlEncoding("UTF-8");// 设置编码
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 二进制

		} catch (IOException e) {
			throw new FtpException("获取ftp链接对象失败", e);
		}
		return ftpClient;
	}

	/**
	 * 关闭ftp链接对象
	 * 
	 * @param ftpClient
	 * @throws FtpException
	 */
	public static void closeFTPClient(FTPClient ftpClient) throws FtpException {
		if (null != ftpClient && ftpClient.isConnected()) {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				throw new FtpException("关闭ftp链接对象失败", e);
			}
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param is
	 *            输入文件流
	 * @param parentDirName
	 *            指定目录
	 * @param fileName
	 *            文件名
	 * @return 访问路径
	 * @throws FtpException
	 */
	public static String uploadFile(InputStream is, String parentDirName, String fileName) throws FtpException {
		logger.info("往:" + parentDirName + "目录,开始上传文件:" + fileName);

		String resultFileName = null;
		FTPClient ftpClient = getFTPClient(parentDirName);
		try {
			// 指定写入目录
			ftpClient.storeFile(new String(fileName.getBytes("utf-8"), "iso-8859-1"), is);
			is.close();
			resultFileName = parentDirName + File.separator + fileName;
			logger.info("上传成功 :" + fileName);
		} catch (Exception e) {
			throw new FtpException("上传文件失败", e);
		} finally {
			closeFTPClient(ftpClient);
		}

		return WEB_URL + resultFileName;
	}

	/**
	 * 下载文件
	 * 
	 * @param fileName
	 * @param parentDirName
	 * @param localPath
	 * @throws FtpException
	 */
	public static void downFile(String fileName, String parentDirName, String localPath) throws FtpException {
		logger.info("开始从ftp服务器下载 :");
		
		FTPClient ftpClient = getFTPClient(parentDirName);
		try {
			// 遍历下载的目录
			FTPFile[] fs = ftpClient.listFiles();
			for (FTPFile ff : fs) {
				// 解决中文乱码问题,两次解码
				byte[] bytes = ff.getName().getBytes("iso-8859-1");
				String fn = new String(bytes, "utf8");
				if (fn.equals(fileName)) {
					File localFile = new File(localPath + fileName);
					OutputStream is = new FileOutputStream(localFile);
					ftpClient.retrieveFile(fileName, is);
					is.close();
					
				}
			}
			ftpClient.logout();
			logger.info("从ftp服务器下载成功 :" + fileName);
		} catch (IOException e) {
			logger.error("下载 出错:", e);
			throw new FtpException("下载出错", e);
		} finally {
			closeFTPClient(ftpClient);
		}
	}

	/**
	 * 从ftp服务器上下载文件到本地
	 * 
	 * @param sourceFileName:服务器资源文件名称
	 * @return InputStream 输入流
	 * @throws IOException
	 * @throws FtpException
	 */
	public static InputStream downFile(String dirName,String sourceFileName) throws FtpException {
		InputStream in = null;
		try {
			in=getFTPClient(dirName).retrieveFileStream(sourceFileName);
		} catch (IOException e) {
			logger.error("下载文件出错", e);
			throw new FtpException("下载文件错误", e);
		} finally {
			closeFTPClient(getFTPClient(dirName));
		}
		return in;

	}

	public static void main(String[] args) throws FtpException,Exception {

		String dirName = "image";
		String fileName = "miaotiao.jpg";
		String localPathUpload = "E:\\ftp_upload\\";
		String localPath = "E:\\ftp_download\\";
		// InputStream is;
		// try {
		// is = new FileInputStream(new File(localPathUpload, fileName));
		// String resName = FtpUtils.uploadFile(is, dirName, fileName);
		// System.out.println(resName);
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// }
		
		/**测试*/
		FtpUtils.downFile(fileName, dirName, localPath);
		
		/**测试*/
//		InputStream is=downFile(dirName, fileName);
//		File file=new File(localPath,fileName);
//		OutputStream os=new FileOutputStream(file);
//		int b;
//		while((b=is.read())!=-1){
//			os.write(b);
//		}
//		is.close();
//		os.close();

	}
}

FtpException.class

package com.test.ftp;

public class FtpException extends Exception {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6664802518263975091L;


	public FtpException(String message, Throwable cause) {
		super(message, cause);
	}

	public FtpException(String message) {
		super(message);
	}

}

三,tomcat更改路径映射 作图片服务器

conf/server.xml文件

<Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">

		<!-- 加上这句 -->
		<Context path="upload" docBase="E://program file//apache-ftpserver-1.0.6//res//home" 
              debug="0" reloadable="false"/> 

</Host>
相关文章
相关标签/搜索