blob文件流转换为url之vue3
需求背景:返回的图片格式为blob类型,需要把图片显示到界面上
实现:
axios.post(downloadUrl,params,{responseType:'blob'}).then((res)=>{
// const blob = new Blob([res.data],{type:'application/vnd.ms-excel'});
const url = window.URL.createObjectURL(res.data);
list[i].url = url
// window.URL.revokeObjectURL(link.href); 无法释放其创建的对象,因为释放后,url不会生效
})
错误的方式:
function downloadFile(url, fileName) {
list.forEach(async (item, i) => {
// 因为双异步所以 该值不会返回来
let resData = await download(i)
console.log(resData);
const url = window.URL.createObjectURL(resData.data);
return url
})
}
function download(i){
// 错误使用
return new Promise((resolve,reject)=>{
// 异步了
axios.post(downloadUrl,params,{responseType:'blob'}).then((res)=>{
resolve(res)
}).catch(err=>{
reject(err)
})
})
// 正确使用
return axios.post(downloadUrl,params,{responseType:'blob'})
}

浙公网安备 33010602011771号