axios Download file

axio request must be added in responseType: 'blob' parameters, as follows

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

  

Which returns the result to do the following treatment

 

.then( res => {
  let blob = new Blob([res], {type: res.type})
  let downloadElement = document.createElement('a')
  let href = window.URL.createObjectURL (blob); // create a download link
  downloadElement.href = href;
  downloadElement.download = fileName; // download file name after
  document.body.appendChild(downloadElement);
  downloadElement.click (); // Download
  document.body.removeChild (downloadElement); // Download the complete removal of elements
  window.URL.revokeObjectURL (href); // release the blob
     
 })

  

Guess you like

Origin www.cnblogs.com/pangguoming/p/11080854.html