使用hutool工具(ZipUtil)對多文件打包壓縮并通過瀏覽器下載
使用hutool工具對多文件進(jìn)行打包壓縮并下載
需求
工作中遇到需要將詳情頁面數(shù)據(jù)導(dǎo)出為word,同時詳情中有圖片和附件,由于附件沒法寫入到word中(可能是自己沒有找到對應(yīng)的解決辦法) , 故將需要導(dǎo)出的word文件,和附件一同打包成zip,進(jìn)行下載
實現(xiàn)
共兩個步驟
1 . 使用hutool對多文件打包
2 .下載
下載方法 FileUtils中的方法文章來源:http://www.zghlxwxcb.cn/news/detail-528739.html
/**
* 下載ZIP壓縮包(會對下載后的壓縮包進(jìn)行刪除)
*
* @param file zip壓縮包文件
* @param response 響應(yīng)
*/
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壓縮包過程發(fā)生異常:", e);
} finally {
if (toClient != null) {
try {
toClient.close();
} catch (IOException e) {
log.error("zip包下載關(guān)流失敗:", e);
}
}
//刪除改臨時zip包(此zip包任何時候都不需要保留,因為源文件隨時可以再次進(jìn)行壓縮生成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文章來源地址http://www.zghlxwxcb.cn/news/detail-528739.html
到了這里,關(guān)于使用hutool工具(ZipUtil)對多文件打包壓縮并通過瀏覽器下載的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!