一、代码
需要hutool的api
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
/**
* 自定义 (zip压缩包/文件) 操作工具类
*/
@Slf4j
@SuppressWarnings("all")
public class ZipFileUtils {
/**
* 生成Zip压缩包 )
*
* @param targetZipFile 生成zip存放的路径
* @param sourceFiles 压缩包中包含的文件集合
* @param dirWithFlag 是否将文件目录一同打包进去 (true:压缩包中包含文件目录,false:压缩包中不包含目录)
*/
public static void generateZip(File targetZipFile, List<File> sourceFiles, boolean dirWithFlag) {
if (CollUtil.isNotEmpty(sourceFiles)) {
File[] fileArr = sourceFiles.toArray(new File[]{});
ZipUtil.zip(targetZipFile, dirWithFlag, fileArr);
}
}
/**
* 下载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", 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();
}
}
/**
* 任何单文件下载
*
* @param file 要下载的文件
* @param response 响应
*/
public static void downloadAnyFile(File file, HttpServletResponse response) {
FileInputStream fileInputStream = null;
OutputStream outputStream = null;
try {
fileInputStream = new FileInputStream(file);
// 清空response
response.reset();
//防止文件名中文乱码
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
//根据文件动态setContentType
response.setContentType(new MimetypesFileTypeMap().getContentType(file) + ";charset=UTF-8");
outputStream = response.getOutputStream();
byte[] bytes = new byte[2048];
int len;
while ((len = fileInputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
二、前端部分
export default {
methods: {
selectExportExcel() {
this.$http({
url: "",
method: "get",
params: {
idList: this.idList
},
//这个不能忘!!!! 否则下载下来的文件都是损坏的!!!
responseType: 'blob'
}).then((response) => {
if (!response) {
return;
}
let link = document.createElement("a");
let filename = response.headers["content-disposition"];
if (filename.indexOf("temp") > 0) {
link.href = filename;
} else {
link.href = window.URL.createObjectURL(new Blob([response.data]));
}
link.target = "_blank";
link.download = decodeURI(filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
}
}
三、调用
List<File> files = new ArrayList<>();
String fileName = "D:/" + System.currentTimeMillis() + ".zip";
//获取文件的前缀
//String baseDir = IAASProperites.newInstance().getUserfilesBaseDir();
ZipFileUtils.generateZip(new File(fileName), files, false);
ZipFileUtils.downloadZip(new File(fileName),response);