1. 打包下载图片(文件)
·ReportFile 实体类 随便你自己怎么写了
·reportFile.getFilePath() 文件存放路径
/**
* @param id
*/
@ResponseBody
@RequestMapping("downloadPicture")
public void downloadPicture(String id, HttpServletResponse response) throws Exception {
String name = UUID.randomUUID().toString().replaceAll("-", "");
if (StringUtils.isNotBlank(id)) {
ReportData report = reportDataService.getReport(id);
List<ReportFile> reportFiles = report.getReportFiles(); //获得好多文件
transToZip(name, reportFiles, response);
}
}
/** * @param userPicturesList * @param response * @throws IOException */ public static void transToZip(String name, List<ReportFile> userPicturesList, HttpServletResponse response) throws IOException { byte[] buffer = new byte[1024]; // file = new File(file.getAbsolutePath() + File.separator + fileName + ".zip"); // // 生成的ZIP文件名为Demo.zip // // String strZipName = "D:\\Demo.zip"; // ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); String downloadFilename = name + ".zip";//文件的名称 downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码 response.setContentType("application/octet-stream");// 指明response的返回对象是文件流 response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名 ZipOutputStream out = new ZipOutputStream(response.getOutputStream()); // 需要同时下载的多个照片文件 List<File> manyFiles = new ArrayList<File>(); for (ReportFile reportFile : userPicturesList) { manyFiles.add(new File(reportFile.getFilePath())); }
// 将文件进行压缩
for (int i = 0; i < manyFiles.size(); i++) {
FileInputStream fis = new FileInputStream(manyFiles.get(i));
out.putNextEntry(new ZipEntry(manyFiles.get(i).getName()));
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
System.out.println("生成照片压缩文件成功");
}