Java把文件压缩然后下载
一边压缩一边下载,前端写法可以参考Java通过流下载文件以及相关优化
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=pdf.zip");
response.setHeader("filename", fileInfo.getFileVersion() + ".zip");
response.setContentLength(allFileSize);
BufferedInputStream bufferedInputStream;
ZipOutputStream zipOut = null;
try {
zipOut = new ZipOutputStream(response.getOutputStream());
for (FileInfo info : fileInfoList) {
bufferedInputStream = new BufferedInputStream(new FileInputStream(info.getAbsolutePath()));
zipOut.putNextEntry(new ZipEntry(info.getFileName()));
int temp = 0;
while ((temp = bufferedInputStream.read()) != -1) { // 读取内容
zipOut.write(temp); // 压缩输出
}
bufferedInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
try {
zipOut.flush();
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}