window.open() 下载文件问题分析

首先这种模式适用于后端返回文件流的模式。

window.open() 打开新的链接,这个链接访问到文件地址之后,就开始下载。其实同理 用a链接下载也是可以的,a链接添加 download 属性,然后herf链接是要下载的文件

原文参考:https://blog.csdn.net/weixin_46074961/article/details/105677732    https://blog.csdn.net/qq_38555490/article/details/99697993

window.open发送的是什么请求?

 window.open 默认get 请求,参数是跟在url后面的查询字符串形式。

如果想发送 post 请求(注意post请求是 发送文件)

原文参考:https://blog.csdn.net/menghuanzhiming/article/details/79298974

如果非要用axios获取文件(如 post 请求等)

this.shopMonthexport(this.getParams)
        .then(res => {
          const blob = new Blob([res.data], {type: "application/msword"});//这里是word文件,可根据需求自行更改
          var contentDisposition = res.headers["content-disposition"];
          var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
          var result = patt.exec(contentDisposition);
          var fileName = result[1];
          if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            var reg = /^["](.*)["]$/g;
            elink.download = decodeURI(fileName.replace(reg, "$1")); //下载后文件名
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);//创建下载的链接
            document.body.appendChild(elink);
            elink.click();//点击下载
            URL.revokeObjectURL(elink.href); //释放掉blob对象
            document.body.removeChild(elink);//下载完成移除元素
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
        })
        .catch(e => {
          console.log(e);
        });

参考:前端下载的几种方式  例子

遇到的问题

1、原因是路径有问题,可能是前端 路径没写对,也可能是后端相应路径还没有东西

2、   今天写出这个错的原因是 路径写错

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值