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请求一致

本文标签: 浏览器文件vueaxiosBlob