Javascript front end downloads file stream code example from background

  • 2021-08-06 20:34:28
  • OfStack

Foreground request data:


url: '/app/downloadApp',
 method: 'get',
 responseType: 'blob',
 params: data

Set the receive parameter format to responseType: 'blob',


downloadFile(res, fileName) {
   if (!res) {
    return
   }
   if (window.navigator.msSaveBlob) { // IE As well as IE Kernel browser 
    try {
     window.navigator.msSaveBlob(res, fileName) // res Returns data for the interface, which has been processed when requesting it. If it is not processed, it needs to be processed by itself before this var data = new Blob([res.data])  Note that it needs to be in the form of an array ,fileName Is the file name after downloading 
     // window.navigator.msSaveOrOpenBlob(res, fileName); // This method is similar to the above method, and the difference can be made by Baidu 
    } catch (e) {
     console.log(e)
    }
   } else {
    let url = window.URL.createObjectURL(new Blob([res]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)//  Filename 
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) //  Download complete remove element 
    window.URL.revokeObjectURL(url) //  Release blob Object 
   }
 },
 download(){
   var data = {
    appId:this.appId
   }
   downloadAppAjax(data).then(res => {
     const filename = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]);
     console.log(filename)
     this.downloadFile(res.data,filename)
   })
  }

Here, downloadAppAjax calls the background interface, requests data, and obtains the data returned by the background without a file name. Finally, it is found that attachment; in the header Content-Disposition attribute; filename = app. jpg

Therefore, we need to take out filename to realize automatic renaming of download. Here we use decodeURI to decode Content-Disposition attribute values and get filename:

decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]);

After getting the file stream and file name, receive the file stream and create the address

let url =window.URL.createObjectURL(new Blob([res]))

Then use the a tag to download.


Related articles: