java调用ftp实现上传下载

package com.sqa.frontinterface.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.List;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.alibaba.nacos.client.utils.EnvUtil.LOGGER;

/**
 * ftp上传下载工具类
 * <p>Title: FtpUtil</p>
 * <p>Description: </p>
 *
 * @version 1.0
 */
@Slf4j
public class Ftp {
    private FTPClient ftpClient;
    private String host;
    private int port;
    private String user;
    private String password;

    public Ftp(String host, int port, String user, String Password) {
        this.host = host;
        this.port = port;
        this.user = user;
        this.password = Password;
        this.ftpClient = new FTPClient();
        ftpClient.enterLocalPassiveMode(); //
    }

    /**
     * @return 判断是否登入成功
     */
    public boolean ftpLogin() {
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        this.ftpClient.setControlEncoding("utf-8");
        this.ftpClient.configure(ftpClientConfig);
        try {
            if (this.port > 0) {
                this.ftpClient.connect(this.host, this.port);
            } else {
                this.ftpClient.connect(this.host);
            }
            // FTP服务器连接回答
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                log.debug("登录FTP服务失败!");
                return isLogin;
            }
            boolean login = this.ftpClient.login(this.user, this.password);
            // 设置传输协议
            this.ftpClient.enterLocalPassiveMode();
            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            log.debug("成功登陆FTP服务器");
            isLogin = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("登录FTP服务失败!");
        }
        this.ftpClient.setBufferSize(1024 * 2);
        this.ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }



    public void download(String filePath, HttpServletResponse response) throws IOException{
        // 获取ftp信息
        // 获取文件名称
        int lastIndexOf = filePath.lastIndexOf("/");
        String basePath=filePath.substring(0,lastIndexOf);
        String fileName=filePath.substring(lastIndexOf+1);
        try {
            // 设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("application/x-msdownload");
            // 设置文件头:最后一个参数是设置下载的文件名并编码为UTF-8
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 建立连接
            connectToServer();
            ftpClient.enterLocalPassiveMode();
            // 设置传输二进制文件
            int reply = ftpClient.getReplyCode();
            ftpClient.changeWorkingDirectory(basePath);
            if(!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                throw new IOException("failed to connect to the FTP Server:"+host);
            }
            // 此句代码适用Linux的FTP服务器
            String newPath = new String(fileName.getBytes("GBK"),"ISO-8859-1");
            // ftp文件获取文件
            InputStream is = null;
            BufferedInputStream bis = null;
            try {
                is = ftpClient.retrieveFileStream(newPath);
                bis = new BufferedInputStream(is);
                OutputStream out = response.getOutputStream();
                byte[] buf = new byte[1024];
                int len = 0;
                while ((len = bis.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeConnect();
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FTPConnectionClosedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            LOGGER.error("ERR : upload file "+ filePath+ " from ftp : failed!", e);
        }
    }
    public void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            LOGGER.error("ftp连接关闭失败!", e);
        }
    }

    /**
     * 连接到ftp服务器
     */
    private void connectToServer() throws Exception {
        if (!ftpClient.isConnected()) {
            int reply;
            try {
                ftpClient=new FTPClient();
                ftpClient.connect(host,port);
                boolean login = ftpClient.login(user, password);
                log.debug(String.valueOf(login));
                reply = ftpClient.getReplyCode();

                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    LOGGER.info("connectToServer FTP server refused connection.");
                }

            }catch(FTPConnectionClosedException ex){
                LOGGER.error("服务器:IP:"+host+"没有连接数!there are too many connected users,please try later", ex);
                throw ex;
            }catch (Exception e) {
                LOGGER.error("登录ftp服务器【"+host+"】失败", e);
                throw e;
            }
        }
    }

    /**
     * 通过ftp下载文件
     * @param filePath  文件路径
     * @param fileName   文件名
     * @param response
     * @throws IOException
     */
    public void downloadReport(String filePath,String fileName, HttpServletResponse response) throws IOException{

        try {
            response.reset();
            // 设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("application/x-msdownload");
            // 设置文件头:最后一个参数是设置下载的文件名并编码为UTF-8
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 建立连接
            connectToServer();
            ftpClient.enterLocalPassiveMode();
            // 设置传输二进制文件
            int reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                throw new IOException("failed to connect to the FTP Server:"+host);
            }
            ftpClient.changeWorkingDirectory(filePath);
            // 此句代码适用Linux的FTP服务器
//            String newPath = new String(filePath.getBytes("GBK"),"ISO-8859-1");
            // ftp文件获取文件
            InputStream is = null;
            BufferedInputStream bis = null;
            try {
                is = ftpClient.retrieveFileStream(fileName);
                bis = new BufferedInputStream(is);
                OutputStream out = response.getOutputStream();
                byte[] buf = new byte[1024];
                int len = 0;
                while ((len = bis.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeConnect();
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FTPConnectionClosedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            LOGGER.error("ERR : upload file "+ filePath+ " from ftp : failed!", e);
        }
    }


    /**
     *
     * @param filePath  文件路径ftp相对路径
     * @param response
     * @param zipName  压缩包名
     * @param ftpFileList
     * @param nameList  文件名
     */
    public void downloadFiles(String filePath, HttpServletResponse response, String zipName, List<String> ftpFileList,List<String> nameList) {

        try {

            // 建立连接
            connectToServer();
            ftpClient.enterLocalPassiveMode();
            // 设置传输二进制文件
            int reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                throw new IOException("failed to connect to the FTP Server:");
            }
            ftpClient.changeWorkingDirectory(filePath); // 转移到FTP服务器目录
//            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zipOut = new ZipOutputStream(baos);

            for (String fileName : nameList) {
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile ftpFile : ftpFiles) {
                    if (ftpFile.getName().equals(fileName)){
                        ZipEntry zipEntry = new ZipEntry(ftpFile.getName());
                        zipOut.putNextEntry(zipEntry);

                        InputStream inputStream = ftpClient.retrieveFileStream(ftpFile.getName());
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            zipOut.write(buffer, 0, bytesRead);
                        }
                        inputStream.close();
                        ftpClient.completePendingCommand();
                    }
                }

                FTPFile file = ftpClient.mlistFile(fileName);
                if (file != null) {
                    ZipEntry zipEntry = new ZipEntry(file.getName());
                    zipOut.putNextEntry(zipEntry);

                    InputStream inputStream = ftpClient.retrieveFileStream(file.getName());
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        zipOut.write(buffer, 0, bytesRead);
                    }
                    inputStream.close();
                    ftpClient.completePendingCommand();
                }
            }

            zipOut.close();
            ftpClient.logout();
            ftpClient.disconnect();

            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(zipName,"uTF-8"));

            OutputStream outputStream = response.getOutputStream();
            baos.writeTo(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值