小菜鸟一枚,如若编写存在错误或者缺陷,我会虚心接受教训。程序中涉及到的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);
      }
    }
  }
代码质量以及逻辑可能存在一定的问题,如果需要借鉴请小心谨慎。

Logo

更多推荐