spring mvc java 把多文件打包成zip,并下载

 2023-09-05 阅读 153 评论 0

摘要:再来一篇 /*** 压缩并导出文件* @param zipPath 压缩文件临时路径 路径最后不要有 /* @param zipName 压缩为文件名 **.zip* @param createFilesPath 需要压缩的文件列表* @param request* @param response* @return* @throws IOException*/publ

再来一篇

/***  压缩并导出文件* @param zipPath 压缩文件临时路径  路径最后不要有 /* @param zipName 压缩为文件名 **.zip* @param createFilesPath 需要压缩的文件列表* @param request* @param response* @return* @throws IOException*/public boolean downloadZip(String zipPath,String zipName,List<String>createFilesPath,HttpServletRequest request,HttpServletResponse response) {//String tmpFileName = "report.zip";  byte[] buffer = new byte[1024];  // String strZipPath = COM_REPORT_PATH+"/"+user.getOid()+"/"+report.getOid()+"/"+tmpFileName;  String strZipPath=zipPath+"/"+zipName;try {  File tmpZip=new File(zipPath);if (!tmpZip.exists())tmpZip.mkdirs();File tmpZipFile = new File(strZipPath);if (!tmpZipFile.exists())tmpZipFile.createNewFile();ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));  // 需要同时下载的两个文件result.txt ,source.txt  File[] file1 =new File[createFilesPath.size()] ;for(int i=0;i<createFilesPath.size();i++){file1[i]=new File(createFilesPath.get(i));}for (int i = 0; i < file1.length; i++) {  FileInputStream fis = new FileInputStream(file1[i]);  out.putNextEntry(new ZipEntry(file1[i].getName()));  //设置压缩文件内的字符编码,不然会变成乱码  out.setEncoding("UTF-8");  int len;  // 读入需要下载的文件的内容,打包到zip文件  while ((len = fis.read(buffer)) > 0) {  out.write(buffer, 0, len);  }  out.closeEntry();  fis.close();  }  out.close();  this.downloadFile(zipPath,zipName,response);  } catch (Exception e) {  e.printStackTrace();}  return true;  }/*** 以压缩文件导出* @param fileName* @param filePath* @param response*/public void downloadFile(String filePath,String fileName,HttpServletResponse response){  response.setCharacterEncoding("utf-8");  // response.setContentType("application/octet-stream");  try {File file=new File(filePath,fileName);// 以流的形式下载文件。BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment;filename=" + fileName);toClient.write(buffer);toClient.flush();toClient.close();} catch (IOException ex) {ex.printStackTrace();}}  


版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/878.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息