小功能实现(十五)POST请求,向后端传递参数,并获取返回的文件流(vue)
·
前言:
- 简单的文件流,前端只需要一个a标签即可
- 但这次需要先传递参数,然后后端处理后再返回文件流
- 总体功能是接受前端传递的数组,然后将文件批量打包,并返回文件流给前端
步骤:
- 导入axios
import axios from 'axios';
- 前端发送请求
//参数分别为请求地址和携带参数,这里传的是字符串格式的数组,太长了所以用POST请求
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();
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)