Java使用FTP下载文件(将流返回给HttpServletResponse)

1.添加依赖

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

2.方法

public static void downloadFTPFile(String path,String fileName, HttpServletResponse response){
        FTPClient ftp = new FTPClient();
        InputStream ins = null;
        OutputStream outputStream = null;
   try {
            //设置连接FTP的超时时间
            ftp.setConnectTimeout(1000 * 60);
            //设置ftp字符集
            ftp.setControlEncoding("UTF-8");
            //设置为被动模式
            ftp.enterLocalPassiveMode();
            //登录
            ftp.connect(ip, 21);
            ftp.login(账号, 密码);
            //验证当前登录状态
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                ftp.disconnect();
            } else {
                //转移到当前文件上一级目录下
                ftp.changeWorkingDirectory(path);
                FTPFile[] fs = ftp.listFiles();
                for (FTPFile ff : fs) {
                    if (ff.getName().equals(fileName)) {
                        //从服务器读取指定的文件
                        ins = ftp.retrieveFileStream(ff.getName());
                        //主动调用一次getreply,解决再次读取返回null的问题
                        ftp.getReply();
                    }
                }
                //设置返回格式,获取到当前文件的输入流并输出
                response.reset();
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                outputStream = response.getOutputStream();
                byte[] b = new byte[1024];
                int len;
                while ((len = ins.read(b)) > 0) {
                    outputStream.write(b, 0, len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ins != null) {
                ins.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            //退出登录
            ftp.logout();
            //验证是否已连接
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        }
}
posted @ 2022-09-19 15:14  幻翎木叶  阅读(1799)  评论(0)    收藏  举报