微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 从请求响应创建PDF不适用于axios,但适用于本机xhr

为了强制从服务器下载PDF,我尝试使用axios和本机xhr对象.原因是我必须发送post请求,因为我向服务器传递了太多数据,所以带有简单链接的选项(如site.ru/download-pdf对我来说不起作用).

即使我最终设法用Xhr做到这一点,我仍然不知道为什么axios方法不起作用.

以下是我用xhr执行此操作的方法,它对我有用:

    let xhr = new XMLHttpRequest()
    xhr.open('POST', Vue.config.baseUrl + `order-results/${id}/export-pdf`, true)
    xhr.setRequestHeader("Authorization", 'Bearer ' + this.token())
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    xhr.responseType = 'arraybuffer'

    xhr.onload = function(e) {
      if (this.status === 200) {
        let blob = new Blob([this.response], { type:"application/pdf" })
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = 'Results.pdf'
        link.click()
      }
    };

    xhr.send("data=" + data);

这是“axios-way”,我实际上得到了具有正确页数的PDF,但它们都是空的:

    axios.post(`order-results/${id}/export-pdf`, {
      data,
      responseType: 'arraybuffer'
    }).then((response) => {
      let blob = new Blob([response.data], { type:"application/pdf" })
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'Results.pdf'
      link.click()
    })

Axios已配置为发送授权令牌.
我把Application / x-www-form-urlencoded放在xhr中,否则我无法在服务器端获取数据.

即使xhr工作,我更喜欢使用axios,因为我到处使用它而且我只是好奇我做错了什么.我尝试了不同的解决方案,只有本地xhr才能完成这项工作.

解决方法:

以下适用于我:

axios.post("http://localhost:8080/reports/my-report/",
        data,
        {
            responseType: 'arraybuffer',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/pdf'
            }
        })
        .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'file.pdf'); //or any other extension
            document.body.appendChild(link);
            link.click();
        })
        .catch((error) => console.log(error));

如果这有帮助,请告诉我.

干杯!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐