前端常见下载方法的总结

2020-07-03  本文已影响0人  菜鸟的平凡之路

常用的下载方式

接口是下载文件的路径

  1. window
  2. location
  3. a
  4. iframe
  5. form的action触发

使用blob下载二进制流

  1. 先请求数据下载
  2. fetch
  3. XMLhTTP
netDiskMaterialFileDownload(filePath,fileName,startFn,endFn,errorFn) {
    startFn()
    axios({
      url: filePath,
      method: 'get',
      responseType: 'blob'
    }).then( res => {
       endFn()
       let blob = new Blob([res.data], {
        type: 'application/octet-stream'  // 下载的文件类型格式(二进制流,不知道下载文件类型可以设置为这个), 具体请查看HTTP Content-type 对照表
      })
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {  // IE下对blob的兼容处理
        window.navigator.msSaveOrOpenBlob(blob, fileName);
        return
      }
      let url = URL.createObjectURL(blob)
      let a = document.createElement('a')
      a.style.display = 'none'
      a.href = url
      a.setAttribute('download', fileName)   // 设置下载的文件名
      document.body.appendChild(a) 
      a.click()
      document.body.removeChild(a)       //下载完成移除dom元素
      URL.revokeObjectURL(url)  //释放blob对象
    }).catch(err => {
      endFn()
      errorFn(err)
    })
  }

大文件下载

临时通过改变axios的超时时间解决
禁止先请求数据然后下载的方式
应该服务设置Content-Type: attachment;filename=xxx (附件) / inline;filename=xxx (内连)
默认是直接打开

上一篇 下一篇

猜你喜欢

热点阅读