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));

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

干杯!

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...