java使用ftp下载文件到本地(只是下载)


1.添加依赖
        camel-ftp依赖与commons-net依赖两者取其中一个即可
        
            org.apache.camel
            camel-ftp
            2.13.2
        

        
            commons-net
            commons-net
            3.6
        

2.辅助类
package com.zq.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;
/**
 * Created by java1 on 2018/1/23 0031.
 */

public class FtpUtil {

    private final static Log logger = LogFactory.getLog(FtpUtil.class);

    /**
     * 获取FTPClient对象
     *
     * @param ftpHost
     *            FTP主机服务器
     * @param ftpPassword
     *            FTP 登录密码
     * @param ftpUserName
     *            FTP登录用户名
     * @param ftpPort
     *            FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.info("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                logger.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.info("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }

    /*
     * 从FTP服务器下载文件
     *
     * @param ftpHost FTP IP地址
     *
     * @param ftpUserName FTP 用户名
     *
     * @param ftpPassword FTP用户名密码
     *
     * @param ftpPort FTP端口
     *
     * @param ftpPath FTP服务器中文件所在路径 格式: zq/ftp路劲    fdfd/aa
     *
     * @param localPath 下载到本地的位置 格式:H:/download
     *
     * @param fileName 文件名称
     */
    public static void downloadFtpFile(String ftpHost, String ftpUserName,
                                       String ftpPassword, int ftpPort, String ftpPath, String localPath,
                                       String fileName) {

        FTPClient ftpClient = null;

        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);

            File localFile = new File(localPath + File.separatorChar + fileName);
            OutputStream os = new FileOutputStream(localFile);
            ftpClient.retrieveFile(fileName, os);
            os.close();
            ftpClient.logout();

        } catch (FileNotFoundException e) {
            logger.error("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            logger.error("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("文件读取错误。");
            e.printStackTrace();
        }

    }



}

3.测试(这一步测试其实是把文件从ftp上拉到(或复制到)本地自定义的文件夹下面)
package com.zq.down;

import com.zq.util.FtpUtil;

/**
 * Created by java1 on 2018/1/23 0023.
 */
public class FtpDownloadTestScriptTest {
    public static void main(String[] args) {
        String ftpHost = "10.1.1.123";
        String ftpUserName = "123";
        String ftpPassword = "123456";
        int ftpPort = 21;
        String ftpPath = "/";//ftp根目录
        String localPath = "E:\\TestTxt";
        String fileName = "c4.zip";
        FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
    }

}

4. (1,2,3步骤是把文件拉到本地,如果说在界面想出现下载界面的话可以发送ajax请求。下面是我写的,仅供参考)
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: "/device/exportLog",
            data: { 'deviceSn': deviceSn } ,
            timeout: 10000,
            success: function ( data ) {
                if(data.status){
                    Messenger().post({
                        message: data.info,
                        type: 'success',
                        showCloseButton: true
                    }) ;
                    var FileName = deviceSn.toLowerCase()+".zip";
                    var url = window.location.protocol + "//" + window.location.host + "/device/deviceLogdownFromHttp?fileName="+FileName;
                    window.location.href = url;
                    }else{
                    Messenger().post({
                        message: data.info,
                        type: 'error',
                        showCloseButton: true
                    }) ;
                }
            }
        });

5.后台:
/**
     * 下载zip文件
     * */
    @RequestMapping("/deviceLogdownFromHttp")
    public void deviceLogdownFromHttp(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String fileName = request.getParameter("fileName");
        try{
            String resultPath =PropertyUtil.getProperty("tasksave.filePath")+"/"+fileName;// "E://AllTxt//zqzipzipzipzipzip.rar";
            String zipName = resultPath.substring(0,resultPath.lastIndexOf(".")) + ".zip";
            File zipFile = new File(zipName);
            //读写zip文件
            InputStream fis = new BufferedInputStream(new FileInputStream(zipFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            response.reset();
            String targetName = zipName.substring(zipName.lastIndexOf("/")+1);
            targetName = new String(targetName.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + targetName + "\"");
            response.addHeader("Content-lenth", "" + buffer.length);
            response.setContentType("application/octet-stream;charset=UTF-8");

            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            os.write(buffer);
            os.flush();
            os.close();
            response.flushBuffer();
    String cc=fileName.substring(0,fileName.lastIndexOf(".")).toUpperCase();
            sysLogMapper.deleteDownloadLogTaskByDeviceSn(fileName.substring(0,fileName.lastIndexOf(".")).toUpperCase());
        }catch(Exception e){
            e.printStackTrace();
        }



    }
6.(4,5步骤仅供参考,每个人写的不一样。)
      主要是:
                    var FileName = deviceSn.toLowerCase()+".zip";
                    var url = window.location.protocol + "//" + window.location.host + "/device/deviceLogdownFromHttp?fileName="+FileName;
                    window.location.href = url;(前台)
    (后台):deviceLogdownFromHttp这个方法



你可能感兴趣的:(ftp)