FTP方式的文件上傳和下載的Java代碼

須要引入:commons-net-3.1.jar , servlet-api-2.5.jar支撐


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

import javax.servlet.http.HttpServletResponse;

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 com.zte.paas.common.SysConstants;

/**
 * 處理Ftp文件的上傳和下載
 *
 * @author zhaofeng
 *
 */
public class FtpTool {

    /**
     * Description: 向FTP服務器上傳文件
     *
     * @param url
     *            FTP服務器hostname
     * @param username
     *            FTP登陸帳號
     * @param password
     *            FTP登陸密碼
     * @param path
     *            FTP服務器保存目錄
     * @param filename
     *            上傳到FTP服務器上的文件名
     * @param input
     *            輸入流
     * @return 成功返回true,不然返回false
     */
    public boolean uploadFile(String url, String username, String password,
            String path, String filename, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(url);
            ftp.login(username, password);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            // 轉到指定上傳目錄
            ftp.changeWorkingDirectory(path);
            ftp.setFileType(FTP.BINARY_FILE_TYPE); // 設置爲2進制上傳
            // 將上傳文件存儲到指定目錄
            ftp.storeFile(filename, input);
            ftp.logout();
            input.close();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    /**
     * Description: 從FTP服務器下載文件
     *
     * @param url
     *            FTP服務器hostname
     * @param username
     *            FTP登陸帳號
     * @param password
     *            FTP登陸密碼
     * @param remotePath
     *            FTP服務器上的相對路徑
     * @param fileName
     *            下載時的默認文件名
     * @param localPath
     *            下載後保存到本地的路徑
     * @return
     */
    public boolean downFile(String url, String username, String password,
            String remotePath, String fileName, HttpServletResponse response) {
        // 初始表示下載失敗
        boolean success = false;
        // 建立FTPClient對象
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            // 鏈接FTP服務器
            // 若是採用默認端口,能夠使用ftp.connect(url)的方式直接鏈接FTP服務器
            ftp.connect(url);
            // 登陸ftp
            ftp.login(username, password);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            String realName = remotePath
                    .substring(remotePath.lastIndexOf("/") + 1);
            // 轉到指定下載目錄
            ftp.changeWorkingDirectory(SysConstants.FTP_PATH);
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            // 列出該目錄下全部文件
            // 設置文件下載頭部
            response.setContentType("application/x-msdownload");// 設置編碼
            response.setHeader("Content-Disposition", "attachement;filename="
                    + new String(fileName.getBytes(), "ISO-8859-1"));
            FTPFile[] fs = ftp.listFiles();
            // 遍歷全部文件,找到指定的文件
            for (FTPFile ff : fs) {
                if (ff.getName().equals(realName)) {
                    OutputStream out = response.getOutputStream();
                    InputStream bis = ftp.retrieveFileStream(realName);

                    // 根據絕對路徑初始化文件
                    // 輸出流
                    int len = 0;
                    byte[] buf = new byte[1024];
                    while ((len = bis.read(buf)) > 0) {
                        out.write(buf, 0, len);
                        out.flush();
                    }
                    out.close();
                    bis.close();
                }
            }
            ftp.logout();
            // 下載成功
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

}
相關文章
相關標籤/搜索