SpringBoot+Vue 结合blob实现流下载功能
涉及技术Springboot + Vue + MyExcel(这里也可以使用自己的文件等)服务端实现@GetMapping(value = "/exportOrderFs")@CrossOriginpublicvoid exportOrderFs(HttpServletResponse response) throws IOException {String path = "/Users/angu
·
涉及技术
Springboot + Vue + MyExcel(这里也可以使用自己的文件等)
服务端实现
@GetMapping(value = "/exportOrderFs")
@CrossOrigin
public void exportOrderFs(HttpServletResponse response) throws IOException {
String path = "/Users/angus/tmp/myexcel-master/example/src/main/resources/templates/";
// get html file
Map<String, Object> dataMap = getDataMap();
try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()){
Workbook workbook = excelBuilder
.fileTemplate(path,"freemarkerToExcelExample.ftl")
.build(dataMap);
AttachmentExportUtil.export(workbook,"月报",response);
//FileExportUtil.export(workbook,new File(path+"测试"));
}
}
这里使用的是AttachmentExportUtil 的一个流工具,实现方式同下
@GetMapping(value = "/exportOrderFs")
@CrossOrigin
public void exportOrderFs(HttpServletResponse response) throws IOException {
String path = "/Users/angus/tmp/myexcel-master/example/src/main/resources/templates/";
// get html file
/**设置头信息*/
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
/**一定要设置成xlsx格式*/
response.setHeader("Content-disposition", "attachment;filename=" + filename);
/**创建一个输出流*/
ServletOutputStream outputStream = response.getOutputStream();
Map<String, Object> dataMap = getDataMap();
try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()){
Workbook workbook = excelBuilder
.fileTemplate(path,"freemarkerToExcelExample.ftl")
.build(dataMap);
/**写入数据*/
workbook.write(outputStream);
/**关闭流*/
outputStream.close();
}
}
Vue实现方式
创建一个请求工具类
getFileRequest(url, params){
let accessToken = getStore('accessToken');
return axios({
method: 'get',
url: `${base}${url}`,
responseType: "blob",
params: params,
headers: {
'accessToken': accessToken,
"Content-Type": "multipart/form-data"
}
});
};
如果请求部分代码不这样写,下载下来的 excel 会乱码哦,主要是 responseType 和 headers 吧!
getFileRequest(url).then(res => {
const link = document.createElement('a');
let blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
link.style.display = 'none';
link.href = URL.createObjectURL(blob);
let num = '';
for (let i = 0; i < 10; i++) {
num += Math.ceil(Math.random() * 10)
}
link.setAttribute('download', 'test.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link)
});
大功告成
更多推荐
已为社区贡献1条内容
所有评论(0)