String newAnName;//新文件名称(表里存的)
String anName;//原文件名称(表里存的)
String anPath = rootDir+"/"+newAnName;//下载路径
// ftp客户端 private FTPClient ftpClient = new FTPClient(); /** ftp文件下载 * @param pathname ftp目录 * @param filename 文件原来名称 * @param filepath 文件下载路径 * @param response * @throws IOException */ public void download(String pathname, String filename,String filepath, HttpServletResponse response) throws IOException { 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(pathname); if(!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } // 此句代码适用Linux的FTP服务器 String newPath = new String(filepath.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*20]; 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) { logger.error("ftp连接被关闭!", e); throw e; } catch (Exception e) { logger.error("ERR!", 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); ftpClient.login(username, password); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); logger.info("connectToServer FTP server refused connection."); } } catch (FTPConnectionClosedException ex) { logger.error("服务器:IP:" + host + "没有连接!", ex); throw ex; } catch (Exception e) { logger.error("登录ftp服务器【" + host + "】失败", e); throw e; } } }