后台需要添加请求头
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"utf-8") + ".xls");
前端下载代码
一定要设置responseType: 'blob'这个配置
this.$http.get('schSettlement/exportSettlementSituation',{responseType: 'blob'}).then((res) => {
if (!res) {
this.$message.error("下载模板文件失败");
return false;
}
const blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
const downloadElement = document.createElement('a');
const href = window.URL.createObjectURL(blob);
let contentDisposition = res.headers['content-disposition']; //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
let result = patt.exec(contentDisposition);
let filename = decodeURI(result[1]);
downloadElement.style.display = 'none';
downloadElement.href = href;
downloadElement.download = filename ; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
})