关于如何将存储在ftp上的文件下载到本地并自由选择保存地址问题

           小菜鸟一枚,如若编写存在错误或者缺陷,我会虚心接受教训。程序中涉及到的ars.getName()到的是String类型
  public void testDownload() {
    // 获取ftp的地址url ,端口号port,用户名username以及password.
    String linuxUrl = GlobalProperties.getProperties("adResourceSynchroUrl");
    int port = Integer.valueOf(GlobalProperties.getProperties("adResourceSynchroPort"));
    String username = GlobalProperties.getProperties("adResourceSynchroUrlUsername");
    String password = GlobalProperties.getProperties("adResourceSynchroPassword");
    FTPClient ftpClient = new FTPClient();
    FileOutputStream fos = null;
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("application/form-data");
    response.setCharacterEncoding("utf-8");
    String tailType = null;
    if (ars.getType() == 0) {
      tailType = "jpg";
    } else {
      tailType = "mp4";
    }
    // 将文件的命名以及格式写进信息头设置中
    response.setHeader("Content-Disposition",
        "attachment;filename=" + ars.getName() + "." + tailType);
    try {
      ftpClient.connect(linuxUrl, port);
      ftpClient.login(username, password);
      String remoteFileName = ars.getSource();
      ftpClient.setBufferSize(1024);
      // 设置文件类型(二进制)
      ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
      // 将ftp上的文件传递给response对象,返回前端。
      ftpClient.retrieveFile(remoteFileName, response.getOutputStream());
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException("FTP客户端出错!", e);
    } finally {
      IOUtils.closeQuietly(fos);
      try {
        ftpClient.disconnect();
      } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("关闭FTP连接发生异常!", e);
      }
    }
  }
代码质量以及逻辑可能存在一定的问题,如果需要借鉴请小心谨慎。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值