使用blob實現下載

前提:

responseType:'blob'
/**
 * 下載文件方法
 * @param {*} param0
 * api: 接口
 * payload: 接口的入參
 * fileName: 導出的文件命名
 */
export const blobDownload = ({ api, payload, fileName = '' }) => {
  let blob = null
  return http(api, payload).then(res => {
    //  此處res裏必須能取得到header
    fileName = fileName || decodeURI(res.headers['content-disposition'].split(';')[1].split('"')[1])
    if (!window.navigator.msSaveOrOpenBlob) {
      blob = new Blob([res.data])
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    } else {
      window.navigator.msSaveOrOpenBlob(blob, fileName)
    }
  })
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章