下载功能。针对要加请求头的下载方式

一般下载,直接调用ifream方式即可。

但是有些下载方式,需要添加请求头,ifream加不了请求头,因此可以参考以下写法:

// 文件下载 && 文件导出
function exportData(obj) {
  let fileType = ''
  if (obj.fileType.indexOf('zip') != -1) {
    fileType = 'application/zip'
  } else if (obj.fileType.indexOf('xlsx') != -1) {
    fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  } else if (obj.fileType.indexOf('xls') != -1) {
    fileType = 'application/vnd.ms-excel'
  } else if (obj.fileType.indexOf('pdf') != -1) {
    fileType = 'application/pdf'
  }

  axios({
    url: obj.url,
    method: obj.method,
    data: obj.data || {},
    responseType: 'blob',
    xsrfHeaderName: 'Authorization',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': getToken()
    },
  }).then(response => {
    let blob = new Blob([response.data], {
      type: fileType
    })
    if (obj.fileType === 'pdf') {
      window.open(window.URL.createObjectURL(blob))
      return
    }
    let url = window.URL.createObjectURL(blob)
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    console.log('response',response,url)
    link.setAttribute('download', obj.fileName)
    document.body.appendChild(link)
    link.click()
  }).catch(error => {
    console.log(error)
  })
}

 

参考demo

// msSaveBlob_testFile.txt为下载的文件名称

window.navigator.msSaveBlob,只提供一个保存按钮。(只针对IE)

 window.navigator.msSaveOrOpenBlob,提供保存和打开按钮。(只针对IE)

  

 1 <html>
 2     <script>
 3         function load(){
 4             var blobObject = new Blob(["I scream. You scream. We all scream for ice cream."]);     
 5                         
 6             if(window.navigator.msSaveBlob){
 7                 // IE浏览器
 8                 //window.navigator.msSaveBlob(blobObject, 'msSaveBlob_testFile.txt');        //只提供一个保存按钮    
 9                 window.navigator.msSaveOrOpenBlob(blobObject, 'msSaveBlob_testFile.txt');    //提供保存和打开按钮        
10                 
11             } else {
12                 // 非IE
13                 const url = window.URL.createObjectURL(blobObject)
14                 let link = document.createElement('a')
15                 link.style.display = 'none'
16                 link.href = url
17                 link.setAttribute('download', 'msSaveBlob_testFile.txt')
18                 document.body.appendChild(link)
19                 link.click()
20                 window.URL.revokeObjectURL(url)
21             }                
22         }    
23     </script>
24     <body onload="load()"></body>    
25 </html>
原文地址:https://www.cnblogs.com/luoxuemei/p/14303166.html