前言:
- 简单的文件流,前端只需要一个a标签即可
- 但这次需要先传递参数,然后后端处理后再返回文件流
- 总体功能是接受前端传递的数组,然后将文件批量打包,并返回文件流给前端
步骤:
import axios from 'axios';
axios.post(process.env.ADMIN_API + '/gim2/downLoadE3ms.do', list_down, { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', '三维成果.zip');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
this.listhbnjm = [];
this.$refs.multipleTable.clearSelection();
})
.catch(error => {
console.error("下载失败");
});
- 后端下载,Controller和ServiceImpl
@RequestMapping(value = "downLoadE3ms.do", method = RequestMethod.POST)
public void downLoadE3ms(@RequestBody String evEntitys, HttpServletResponse response) throws Exception {
evGimcheckTaskService.downLoadE3ms(evEntitys, response);
}
public void downLoadE3ms(String evEntitys, HttpServletResponse response) throws Exception {
List<EvEntity> evEntities = JSONObject.parseArray(evEntitys, EvEntity.class);
ArrayList<Map<String,String>> pathList = new ArrayList<>();
String path="";
for (EvEntity evEntity : evEntities) {
String gimName=evEntity.getGimName().substring(0,evEntity.getGimName().indexOf("."));
Map<String,String> pathMap=new HashMap<>();
path="...";
pathMap.put("path",path);
pathMap.put("gimName",gimName);
pathList.add(pathMap);
}
FileUtil.downE3ms(pathList,response);
}
public static void downE3ms(List<Map<String,String>> pathList, HttpServletResponse response) throws IOException {
byte[] buf = new byte[1024];
BufferedOutputStream bos = null;
ZipOutputStream out = null;
try {
bos = new BufferedOutputStream(response.getOutputStream());
response.reset();
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition","attachment;filename="+"阿弥陀佛.zip");
out = new ZipOutputStream(bos);
for (Map<String,String> path : pathList) {
File zip = ZipUtil.zip(path.get("path"));
FileInputStream in = new FileInputStream(zip);
out.putNextEntry(new ZipEntry(path.get("gimName")+".zip"));
int len = -1;
while ((len=in.read(buf))!=-1){
out.write(buf,0,len);
}
in.close();
zip.delete();
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out!=null)
out.close();
if (bos!=null)
bos.close();
}
}