ftp 文件上传、下载

依赖库:commons-net-1.4.1.jar,commons-io-1.4.jar,commons-fileupload-1.2.1.jar

package gz.ads.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.InputStream;

public class FtpUtil {

    private FTPClient ftpClient;

    private static final String remoteAddress = Messages.getString("ftp.remoteAddress");
    private static final String remotePort = Messages.getString("ftp.remotePort");
    private static final String userName = Messages.getString("ftp.userName");
    private static final String password = Messages.getString("ftp.password");
    private static final String remotePath = Messages.getString("ftp.remotePath");

    private FtpUtil() {
    }

    public static FtpUtil getInstance() {
        return new FtpUtil();
    }

    public void connectServer(String remotePath) {
        try {
            if (remotePath == null) {
                remotePath = FtpUtil.remotePath;
            }

            ftpClient = new FTPClient();

            if (remotePort == null || 0 == Integer.parseInt(remotePort)) {
                ftpClient.connect(remoteAddress);
            } else {
                ftpClient.connect(remoteAddress, Integer.parseInt(remotePort));
            }

            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                closeConnect();
                System.exit(1);
            }

            ftpClient.login(userName, password);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.println(" login success !!! ");

            if (remotePath.length() != 0) {
                boolean flag = alertWorkingDirectory(remotePath);
                if (flag) {
                    System.out.println(" set working directory successful !!! ");
                }
            }
        } catch (IOException e) {
            System.out.println(" not login !!! ");
            e.printStackTrace();
        }
    }

    public void connectServer() {
        connectServer(null);
    }

    public void closeConnect() {
        try {
            ftpClient.disconnect();
            System.out.println(" disconnect success !!! ");
        } catch (IOException e) {
            System.out.println(" not disconnect !!! ");
            e.printStackTrace();
        }
    }

    // 创建工作目录,并将当前工作目录定位到新创建的目录
    // 采用一次命令创建一个文件夹的方式,已兼容 IBM FTP
    public boolean alertWorkingDirectory(String path) throws IOException {
        boolean flag = ftpClient.changeWorkingDirectory(path);
        if (!flag) {
            String ps[] = path.split("/");
            for (int i = 0; i < ps.length; i++) {
                if (!ftpClient.changeWorkingDirectory(ps[i])) {
                    if (ftpClient.makeDirectory(ps[i])) {
                        flag = ftpClient.changeWorkingDirectory(ps[i]);
                    } else {
                        flag = false;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 文件上传
     *
     * @param path        文件保存路径
     * @param fileName
     * @param inputStream
     * @return
     */
    public boolean upload(String path, String fileName, InputStream inputStream) {
        boolean flag = false;
        try {
            alertWorkingDirectory(path);
            flag = ftpClient.storeFile(fileName, inputStream);
            if (flag) {
                System.out.println(" upload success !!! ");
            }
        } catch (IOException e) {
            System.out.println(" not upload !!! ");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 文件下载
     *
     * @param fileName 文件的完整路径
     * @return
     */
    public InputStream download(String fileName) {
        InputStream inputStream = null;
        try {
            inputStream = ftpClient.retrieveFileStream(fileName);
        } catch (IOException e) {
            System.out.println(" not download !!! ");
            e.printStackTrace();
        }
        return inputStream;
    }
}
<form action="ftp" method="post" enctype="multipart/form-data" >
	<input type="file" name="uf"/>
	<button type="submit">submit</button>
</form>
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import ftp.FtpUtil;

public class FtpServlet extends HttpServlet {

	private static final long serialVersionUID = 3779694262336394810L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			Iterator iter = upload.parseRequest(request).iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				InputStream inputStream = item.getInputStream();
				FtpUtil ftpUtil = FtpUtil.getInstance();
				ftpUtil.connectServer();
				ftpUtil.upload("test", item.getName().substring(
						item.getName().lastIndexOf("\\") + 1,
						item.getName().length()), inputStream);
				ftpUtil.closeConnect();
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(java,ftp,下载,上传)