java FtpClient文件下载方法

public void downloadFileStream(HttpServletResponse response, String path, String fileName) {
   OutputStream outputStream = null;
   FTPClient ftpClient = getFtpClient();

   InputStream in = null;
   BufferedInputStream bis = null;
   try {
      int index = path.indexOf("/");
      int index1 = path.indexOf("/", index + 2);
       //文件路径 去除掉ftp地址
       String filePath = path.substring(index1)
      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
      // 设置文件ContentType类型,这样设置,会自动判断下载文件类型
      response.setContentType("application/x-msdownload");
      // 设置文件头:最后一个参数是设置下载的文件名并编码为UTF-8
      response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
      // 此句代码适用Linux的FTP服务器
      String newPath = new String(fileName.getBytes("GBK"), StandardCharsets.ISO_8859_1);
      ftpClient.enterLocalPassiveMode();  // 设置被动模式,开通一个端口来传输数据
      boolean result = existFile(filePath, ftpClient);
      if (result) {
         ftpClient.changeWorkingDirectory(path);
         in = ftpClient.retrieveFileStream(newPath);
         bis = new BufferedInputStream(in);
         outputStream = response.getOutputStream();
         byte[] buf = new byte[1024];
         int len = 0;
         while ((len = bis.read(buf)) > 0) {
            outputStream.write(buf, 0, len);
         }
         outputStream.flush();

      }
   } catch (IOException e) {
      log.error("下载文件出错!", (Object) e.getStackTrace());
   } finally {
      releaseFtpClient(ftpClient);
      if (null != outputStream) {
         try {
            outputStream.close();
         } catch (IOException e) {
            log.error("关闭输出流出错!", (Object) e.getStackTrace());
         }
      }
      if (bis != null) {
         try {
            bis.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      if (in != null) {
         try {
            in.close();
     //需要注意,在使用ftpClient.retrieveFileStream,一定要加completePendingCommand()
//调用这个接口后,一定要手动close掉返回的InputStream,然后再调用completePendingCommand方法,若不是按照这个顺序,则会导致后面对FTPClient的操作都失败
            ftpClient.completePendingCommand();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值