第一种
- 请求api中的response类型必须添加
responseType: "blob"
(因为response回传不存在blob类型,默认字符串,会导致下载的文件无法解析)
// 导出用户登录日志
exportJournalLogin(params) {
return http({
url: `Journal/Login/Export`,
method: 'POST',
data: params,
responseType: 'blob'
})
},
const blob = new Blob([res]);
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = `XX文档计算书.docx`;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
download(){
// 这里是将链接地址url转成blob地址,fetch(url)是请求后台接口
fetch(url).then(res => res.blob()).then(blob => {
const downloadElement = document.createElement('a');
downloadElement.href = URL.createObjectURL(blob)
// 下载文件的名称及文件类型后缀
downloadElement.download = "小明.pdf";
document.body.appendChild(link)
link.click()
//在资源下载完成后 清除 占用的缓存资源
window.URL.revokeObjectURL(downloadElement.href);
document.body.removeChild(downloadElement);
});
}
第二种
let url = window.URL.createObjectURL(new window.Blob([res]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', `${this.currentRobot.name}-版本流程数据.xls`)
document.body.appendChild(link)
link.click()
link.parentNode.removeChild(link)
第三种(和第一种差不多)
/**
* 下载文件
* res 为二进制流文件
* item 为这条数据,包含名称即可,随机应变
* docFormat 为文件格式,默认 MP3
*/
downloadBlob(res, item, docFormat) {
const endFormat = docFormat || 'mp3'
let link = document.createElement('a')
link.style.display = 'none'
link.href = window.URL.createObjectURL(res)
link.download = this.$route.query.bookName + '-' + item.chapterName + '.' + endFormat
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(link.href) // 释放URL 对象
document.body.removeChild(link)
},