做pdf文件下载的时候,后端返回了二进制数据流,前端在发起请求时需要设置responseType: arraybuffer 或者blob类型才可以,具体操作可以看我之前的文章(传送门)。一开始对接的时候下载打开都是正常的,过后突然就不行了,能下载成功,页数也是正常的,但是打开页面却都是空白的。

搜索百度了一番,都是说设置好response Type就可以了,偶然发现有人评论说不能用axios请求要用原生的Ajax请求才可以,试了一下果然成功了。

具体代码:

downloadFn() {
      let that = this;
      this.loading = true;
      var xhr = new XMLHttpRequest(); // 用这种原生请求下载后端返回的二进制流打开就不会出现空白
      xhr.open(
        "get",
        "/server-api/api/system/rest/s/apply/agree-document/get?userId=" +
          this.userId,
        true
      );
      xhr.responseType = "blob";
      xhr.onload = function() {
        that.loading = false;
        const url = window.URL.createObjectURL(this.response);
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", "渊亭科技服务协议.pdf");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      };
      xhr.send();
    },

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐