直接下载

前端创建超链接

<a :href='"/user/downloadExcel"'>下载模板</a>

点击事件触发

function downloadExcel() {
window.location.href = "/user/downloadExcel";
}

token下载

注:数据返回类型必须为 responseType: ‘blob’

1.数据正常,后台返回 blob 文件流
2.数据异常,后台返回 blob 类型异常信息

const downLoadFile = function (response, fileName){
if(response.type === 'jsonString' || response.type === 'application/json') {
let reader = new FileReader();
reader.readAsText(response, 'utf-8');
reader.onload = e =>{
// 后台返回文件下载失败 处理
const { msg } = JSON.parse(reader.result);
this.$Message.error(msg);
}
}else {
if (window.navigator.msSaveOrOpenBlob) { // IE10
navigator.msSaveBlob(response, fileName);
}else {
let $body = document.body;
let link = document.createElement('a');
link.style.display = 'none';
$body.appendChild(link);
link.href = URL.createObjectURL(response); //创建一个指向该参数对象的url
link.download = fileName;
link.click(); // 触发下载
URL.revokeObjectURL(link.href); // 释放创建的URL
$body.removeChild(link)
link = null
}
}
}