功能背景:
项目中使用vue作为框架,以axios方式来发送post请求,后台返回了一个包含了excel文件流的response。
遇到的问题:
调用了接口之后,不报错也不进行下载
遇到问题的原因:
是由于ajax请求只是一个字符型的请求,但是文件是以二进制进行传输的,ajax无法解析后台返回的文件流,因此,调用无反应。
解决:
在调用下载接口的时候,规定responseType:‘blob’,表示后台传来的数据用blob对象接收
以下是解决之后的前端代码
exportExcel(ids){
if (ids instanceof Array && ids.length < 1) {
this.$notification.error({
message: "请选择要导出的数据!",
});
return;
}
let formData = new FormData();
formData.append("ids",ids)
axios({ // 用axios发送post请求
method: 'post',
url: api.exportDictionaryExcel(), // 请求地址
data: formData, // 参数
responseType: 'blob' // 表明返回服务器返回的数据类型
})
.then((res) => { // 处理返回的文件流
const content = res
const blob = new Blob([content])
console.log(content)
const fileName = 'xxx.xlsx'
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
}
})
},
以下是解决之后的后端代码
public static void download(Workbook wb, HttpServletResponse response, String returnName) throws IOException{
response.setContentType("application/octet-stream;charset=UTF-8");
// 保存的文件名,必须和页面编码一致,否则乱码
returnName = URLEncoder.encode(returnName, "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + returnName);
wb.write(response.getOutputStream());
}