记录一次文件下载时的bug

文件下载

文件下载是一个比较常见的需求,最近在实现移动端文件下载时遇到了下载文件出现CORS的问题。
解决路程:起初,发现是后端的代理没有配置好;后端代理映射配置好后,发现移动端文件下载还是不行,后来发现pc端下载是成功的;
这就很奇怪了呀(陷入了思维定势,查看代码会自动忽略某些东西,这个时候就应该摇人了)。最后发现代码有问题,url带有http,下载请求时改写了请求头,携带了token。。。

上正确代码

axios({
        //
        url: file.fileUrl,
        method: 'get',
        headers: { //这里我把token信息去掉了
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        responseType: 'blob',
        // `onDownloadProgress` 允许为下载处理进度事件
        onDownloadProgress: this.onDownloadProgress,
      })
        .then((res) => {
          const { data, headers } = res
           const fileName = headers['content-disposition'].replace(
             /\w+;filename=(.*)/,
             '$1'
           )
          const blob = new Blob([data], { type: headers['content-type'] })
          const url = window.URL.createObjectURL(blob)
          this.dom.href = url  	//这个dom保存的是a链接dom对象
          this.dom.download = decodeURI(fileName)
          this.dom.style.display = 'none'
          document.body.appendChild(this.dom)
          this.dom.click()
        })
        .catch((err) => {
          console.log(err)
        })

附:fetch请求

fetch请求下载文件和axios下载都类似,先是获取blob对象,然后利用a链接或者window下载。当然,如果后端给的是一个带http的url没有其他需求可以直接使用a链接和window对象下载文件。

fetch(url, {
        headers: new Headers({
          Origin: location.origin,
        }),
        mode: "cors",
      })
        .then((res) => res.blob())
        .then((blob) => {
          const blobUrl = window.URL.createObjectURL(blob);
          if (isIE() || isEdge()) {
            window.navigator.msSaveOrOpenBlob(blob, fileName);
          } else {
            const url = window.URL || window.webkitURL || window.moxURL;
            const downloadHref = url.createObjectURL(blob);
            const downloadLink = document.createElement("a");
            downloadLink.href = downloadHref;
            downloadLink.download = fileName;
            downloadLink.click();
          }
          window.URL.revokeObjectURL(blobUrl);
        });

阿巴阿巴…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZSK6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值