第一种
importTemplateExcel() {
Api.importTemplateExcel(this.downloadUrl,{}).then(resp=>{
if (resp && resp.size > 0) {
let url = window.URL.createObjectURL(new Blob([resp]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
// 设置下载的文件名
link.setAttribute('download', `${this.downloadName}_${new Date().getTime()}.xlsx`)
document.body.appendChild(link)
link.click()
} else {
this.$message.error('暂无数据')
}
})
},
第二种,封装
export function download(url, params, filename) {
console.log(url)
downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
return service.get(url, params, {
transformRequest: [(params) => { return tansParams(params) }],
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
responseType: 'blob'
}).then(async (data) => {
const isLogin = await blobValidate(data);
console.log(isLogin)
if (isLogin) {
const blob = new Blob([data])
saveAs(blob, filename)
} else {
const resText = await data.text();
const rspObj = JSON.parse(resText);
const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
Message.error(errMsg);
}
downloadLoadingInstance.close();
}).catch((r) => {
console.error(r)
Message.error('下载文件出现错误,请联系管理员!')
downloadLoadingInstance.close();
})
}
// 验证是否为blob格式
async function blobValidate(data) {
try {
const text = await data.text();
JSON.parse(text);
return false;
} catch (error) {
return true;
}
}
/**
* 参数处理
* @param {*} params 参数
*/
function tansParams(params) {
let result = ''
for (const propName of Object.keys(params)) {
const value = params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof (value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key] !== null && typeof (value[key]) !== 'undefined') {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
result += subPart + encodeURIComponent(value[key]) + "&";
}
}
} else {
result += part + encodeURIComponent(value) + "&";
}
}
}
return result
}
调用
importTemplateExcel() {
this.download(
this.downloadUrl,
{},
`${this.downloadName}_${new Date().getTime()}.xlsx`
);
},