js下载文件并重命名

推荐方案,亲测有效

  const downloadFile = (url: string, fileName: string) => {
    //fileurl文件地址(一般是接口返回) filename文件下载后的名字
    const x = new XMLHttpRequest()
    x.open('GET', url, true)
    x.responseType = 'blob'
    x.onload = function () {
      const url = window.URL.createObjectURL(x.response)
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      a.click()
      document.body.removeChild(a)
      // 然后移除
    }
    x.send()
  }

以下方式 attname 和 a.download 属性在跨域请求无效

 window.open(item.docUrl+`?attname=${item.name}`)
    const a = document.createElement('a')
    a.href = item.docUrl
    a.download = item.name
    a.target = '_blank'
    a.click()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容