admin管理员组文章数量:1530518
背景
在vue中,使用axios向后台请求数据,但只接收返回的response并不能实现浏览器下载,所以需要借助于blob实现文件的浏览器下载,分为两种情况,一种是get请求,使用params,另一种使用post请求,参数使用formdata传参
情景1:get请求,params传参
- url与参数部分代码:
this.axios.get('/api/downloadConfig', {
params:{oid:oid},
responseType:'blob',
})
- blob具体下载实现代码
if(res.status === 200){
const content = res.data;
const blob = new Blob([content]);
if('download' in document.createElement('a')){
//非IE下载
const a = document.createElement('a');
a.download = fileName;
a.style.display = 'none';
a.href = window.URL.createObjectURL(blob);
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}else{
//IE10+下载
if(typeof window.navigator.msSaveBlob !== 'undefined'){
window.navigator.msSaveBlob(blob, _this.selected);
}else{
let URL = window.URL || window.webkitURL;
let downloadUrl = URL.createObjectURL(blob);
window.location = downloadUrl;
}
}
情景2:post请求,formdata传参
- url与参数部分代码:
this.axios.post('/api/downloadConfig', form, {responseType:'blob'})
- blob具体下载实现代码与上文get请求一致
版权声明:本文标题:vue中axios利用blob实现文件浏览器下载 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1725950093a1050361.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论