1.首先一般使用文件id向后端发送请求获取相应的文件流
async down(item) {
//下载
const res = await requestDownLoadFile({
Id: item.uid
})
console.log('resssssss',res);
// let res.data= Blob {size: 0, type: 'text/xml'}
//let item ={
//"uid": "74fd9a66-41e3-4769-9201-9bb4893e4831",
//"name": "abaaba",
// "ftype": "jpg",
//"isShow": false,
//"curPercentage": 100,
//"status": "success"
//}
this.getDownLoadFile(res.data, res['headers']['content-type'], item)
},
2.通过new Blob获取blob对象
getDownLoadFile(blobFile, contenttype, row) {
let downloadBolb = null
let fileType = row.ftype
// 后台接口方法url:接口地址,data给后台传的参数
let type = null
if (fileType) {
type = fileTypeMap[fileType]
downloadBolb = new Blob([blobFile], {
type: type
})
// 下载文件
this.downloadFile(downloadBolb, row.name + '.' + fileType)
return downloadBolb
}
},
3.通过a标签和window.createObjectURL()实现文件下载
downloadFile(blob, fileName) {
let eleLink = document.createElement('a')
eleLink.download = fileName
eleLink.style.display = 'none'
// 字符内容转变成blob地址
eleLink.href = this.getObjectURL(blob)
// 自动触发点击
document.body.appendChild(eleLink)
eleLink.click()
// 然后移除
document.body.removeChild(eleLink)
},
getObjectURL(file) {
let url = null
if (window.createObjectURL !== undefined) {
// basic
url = window.createObjectURL(file)
} else if (window.webkitURL !== undefined) {
// webkit or chrome
try {
url = window.URL.createObjectURL(file)
} catch (error) {}
} else if (window.URL !== undefined) {
// mozilla(firefox)
try {
url = window.URL.createObjectURL(file)
} catch (error) {}
}
return url
},