1、多文件压缩,功能代码如下:
public static boolean downLoadMany(List<File> list, String attachmentName, HttpServletResponse response) throws Exception {
boolean bool = false;
BufferedInputStream bis = null;
String zipPath = AppConst.UPLOAD_PATH + attachmentName + ".zip";
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath));
String fileName = "";
for (int i = 0; i < list.size(); i++) {
String n = list.get(i).getName();
fileName = n + n.substring(n.lastIndexOf("."));
bis = new BufferedInputStream(new FileInputStream(list.get(i)));
ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int num = -1;
while ((num = bis.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, num);
}
zipOutputStream.closeEntry();
bis.close();
}
zipOutputStream.close();
bool = true;
} catch (Exception e) {
e.printStackTrace();
bool = false;
}
return bool;
}
2、zip下载
public static void downLoad_HTTP(HttpServletResponse response) {
String zipPath = "绝对路径/images1.zip";
try {
File file = new File(zipPath);
if (!file.exists()) return;
String name = URLEncoder.encode(file.getName(), "UTF-8");
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.addHeader("Access-Control-Allow-Origin","*");
response.setHeader("Content-Disposition", "attachment;filename=" + name);
toClient.write(buffer);
toClient.flush();
toClient.close();
file.delete();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
3、前端请求代码,其中responseType是重点,这是个巨坑
export const cutImageBase64 = (data = {}) => {
return axios.request({
url: '/user/cutImageBase64',
method: 'post',
data,
responseType: 'blob'
})
}