常规前后端不分离生成压缩包步骤如下:
1.添加ZipUtil工具类
2.使用
/**
* 设置下载文件的response信息
* @param filename 下载文件名
*/
private static void setResponse(String filename, HttpServletResponse response) throws UnsupportedEncodingException {
// 清除首部的空白行(针对jsp文件编译后生成html时产生的空白行)
response.reset();
// 自动判断下载文件类型
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
}
前后端分离实现压缩包的思路如下:
1.查询数据库,获取下载文件的链接
2.将链接的文件读取为文件输入流
3.将流以blob形式response至前端
4.前端接收blob,生成zip
1.ZipUtil
package com.example.springboottest.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
@author l
@date 2020-11-30 18:50
*/
public class ZipUtil {
private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);
/**
* 将压缩文件下载到本地
*/
public static void doZip(String zipFilename, Map<String, InputStream> isMap, String localPath) throws IOException {
log.info("==> 开始下载zip文件{}到:{}", zipFilename, localPath);
doZip(zipFilename, isMap, new FileOutputStream(localPath));
}
/**
* 通过浏览器下载压缩文件
*/
public static void doZip(String zipFilename, Map<String, InputStream> isMap, HttpServletResponse response) throws IOException {
log