關於文件下載的那點事

後端返回Blob形式的文件流  前端接受文件流  並下載

前端需要做多瀏覽器的兼容

if(response.headers['content-type'] == 'application/vnd.ms-excel;charset=utf-8'){
    let type = response.headers['content-type'];
    let fileName = decodeURI(response.headers['content-disposition'] + '').replace('attachment;filename=', '');
    var blob = new Blob([response.data], {type: 'application/vnd.ms-excel;charset=utf-8'})
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(blob, fileName)
    } else {
      let URL = window.URL || window.webkitURL
      let objectUrl = URL.createObjectURL(blob)
      if (fileName) {
        var a = document.createElement('a')
        if (typeof a.download === 'undefined') {
          window.location = objectUrl
        } else {
          a.href = objectUrl
          a.download = fileName
          document.body.appendChild(a)
          a.click()
          a.remove()
        }
      } else {
        window.location = objectUrl
      }
      URL.revokeObjectURL(objectUrl)
    }
  }

注意:請求的時候 responseType 要進行設置

responseType:'arraybuffer'

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章