axios 下载文件

axio请求里必须加  responseType: 'blob' 参数,如下

//下载文件
api.download=function(id) {
  return request({
    url: this.baseUrl+'/download/'+id,
    method: 'get',
    params: {},
    responseType: 'blob'
  })
}

  

返回结果里面要做如下处理

.then( res => {
  let blob = new Blob([res], {type: res.type})
  let downloadElement = document.createElement('a')
  let href = window.URL.createObjectURL(blob); //创建下载的链接
  downloadElement.href = href;
  downloadElement.download = fileName; //下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  window.URL.revokeObjectURL(href); //释放blob对象
     
 })

  

猜你喜欢

转载自www.cnblogs.com/pangguoming/p/11080854.html
今日推荐