通过HTTP请求获取数据(resData),然后使用浏览器的下载功能将数据保存到本地文件

需要下载一个文件到本地保存的时候,前端需要做以下:

        this.$http.getApi(postData).then(resData => {
            let url = window.URL.createObjectURL(resData);
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            let storage = window.localStorage;
            let newFileName = storage.getItem("nowExportFileName");
            console.log(newFileName);
            link.setAttribute(
              "download",
              newFileName && newFileName != "undefined" ? newFileName : fileName
            );
            document.body.appendChild(link);
            link.click();
          });
  1. this.$http.getApi(postData).then(resData => { ... });发起一个HTTP GET请求,使用 this.$http.getApi 方法,postData 是请求的数据。当请求成功后,执行回调函数,将返回的数据保存在 resData 中。

  2. let url = window.URL.createObjectURL(resData);使用 window.URL.createObjectURL 方法创建一个 Blob URL,该 URL 可以代表二进制数据(例如文件内容)。

  3. let link = document.createElement("a");创建一个 a 元素,用于模拟点击下载链接。

  4. link.style.display = "none";link 元素设置为不可见,以确保用户不会看到这个元素。

  5. link.href = url;将链接的 href 属性设置为之前创建的 Blob URL,这样点击链接时将会下载对应的数据。

  6. let storage = window.localStorage;获取本地存储对象。

  7. let newFileName = storage.getItem("nowExportFileName");从本地存储中获取名为 "nowExportFileName" 的项,这可能是一个用于指定下载文件名的值。

  8. console.log(newFileName);在控制台输出 newFileName,用于调试和验证。

  9. link.setAttribute("download", newFileName && newFileName != "undefined" ? newFileName : fileName);设置 link 元素的 download 属性,该属性指定下载文件时的文件名。如果存在 newFileName 且不是 "undefined",则使用 newFileName,否则使用默认的 fileName

  10. document.body.appendChild(link);:将 link 元素添加到文档的 body 中。

  11. link.click();模拟点击链接,触发文件下载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值