最近公司的项目是让前端有让用户下载zip压缩包(里面都是图片,图片是保存在ftp上的)的任务,经过调研,将最终方案复制在下面:
//zip文件的下载 @GetMapping("/zip/{imagePath}") @ResponseBody public void zip(HttpServletResponse response, @PathVariable(value = "imagePath", required = false) String imagePathList) throws IOException { String[] imagePaths = imagePathList.split(CCPCommon.CCP_SEPARATOR); //设置返回响应头 response.reset(); // 自动判断下载文件类型 response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("picture.zip", "UTF-8")); FTPClient ftpClient; ftpClient = FtpUtil.getFTPClient("xxx", "xxx", "xxx", 21); // 中文支持 ftpClient.setControlEncoding("UTF-8"); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory("ftp://xxx"); ZipOutputStream zos = null; OutputStream os = response.getOutputStream(); try { zos = new ZipOutputStream(os); InputStream ins = null; for (String imagePath : imagePaths) { if (imagePath == null || imagePath.equals("") || imagePath.equals("undefined")) {//如果书没有上传 continue; } ins = ftpClient.retrieveFileStream(new String(imagePath.getBytes("UTF-8"), "iso-8859-1")); if (ins != null) { zos.putNextEntry(new ZipEntry(imagePath)); int len; byte[] buff = new byte[1024]; while (-1 != (len = ins.read(buff, 0, buff.length))) { zos.write(buff, 0, len); } zos.closeEntry(); ins.close(); ftpClient.completePendingCommand();//不让一个循环后ftpClient自动关闭 } } zos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
这里很重要的操作:
//设置返回响应头 response.reset(); // 自动判断下载文件类型 response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("picture.zip", "UTF-8"));
一定要设置响应头部的type,并且可以给这个压缩包起一个名字。
还有就是ftp的一个细节:
ftpClient.completePendingCommand();
如果不加这一行,ftp自动会关闭连接,一定要让它保持连接状态。