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(); } } } }
java FtpClient文件下载方法
最新推荐文章于 2025-03-13 14:57:09 发布