使用hutool工具(ZipUtil)对多文件打包压缩并通过浏览器下载
使用hutool工具对多文件进行打包压缩并下载
需求
工作中遇到需要将详情页面数据导出为word,同时详情中有图片和附件,由于附件没法写入到word中(可能是自己没有找到对应的解决办法) , 故将需要导出的word文件,和附件一同打包成zip,进行下载
实现
共两个步骤
1 . 使用hutool对多文件打包
2 .下载
下载方法 FileUtils中的方法文章来源:https://www.toymoban.com/news/detail-528739.html
/**
* 下载ZIP压缩包(会对下载后的压缩包进行删除)
*
* @param file zip压缩包文件
* @param response 响应
*/
public static void downloadZip(File file, HttpServletResponse response) {
OutputStream toClient = null;
try {
// 以流的形式下载文件。
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
toClient = new BufferedOutputStream(response.getOutputStream());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
toClient.write(buffer);
toClient.flush();
} catch (Exception e) {
log.error("下载zip压缩包过程发生异常:", e);
} finally {
if (toClient != null) {
try {
toClient.close();
} catch (IOException e) {
log.error("zip包下载关流失败:", e);
}
}
//删除改临时zip包(此zip包任何时候都不需要保留,因为源文件随时可以再次进行压缩生成zip包)
file.delete();
}
}
public void exportWord(@RequestHeader Long projectId,HttpServletResponse response, Long recordId) {
try {
// 压缩到的位置
File zipFile = new File("D:\\压缩.zip");
// 压缩文件中包含的文件列表,此处为测试代码,实际为自己需要的文件列表
List<File> fileList = CollUtil.newArrayList();
fileList.add(new File("D:\\文件1.doc"));
fileList.add(new File("D:\\文件2.xlsx"));
// 压缩多个文件,压缩后会将压缩临时文件删除
ZipUtil.zip(zipFile, false, fileList.toArray(new File[fileList.size()]));
// 下载
FileUtils.downloadZip(zipFile,response);
} catch (Exception e) {
logger.error("文件压缩异常",e);
} finally {
}
}
参考:https://blog.csdn.net/weixin_44684303/article/details/128723675文章来源地址https://www.toymoban.com/news/detail-528739.html
到了这里,关于使用hutool工具(ZipUtil)对多文件打包压缩并通过浏览器下载的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!