使用jquery AJAX 下载pdf文件

ujv3wf0j  于 2023-01-16  发布在  jQuery
关注(0)|答案(5)|浏览(348)

我想下载jquery AJAX 响应的pdf文件,Ajax响应包含pdf文件数据,我试过这个solution,我的代码如下,但总是得到一个空白的pdf。

$(document).on('click', '.download-ss-btn', function () {

    $.ajax({
        type: "POST",
        url: 'http://127.0.0.1:8080/utils/json/pdfGen',
        data: {
            data: JSON.stringify(jsonData)
        }

    }).done(function (data) {
        var blob = new Blob([data]);
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "Sample.pdf";
        link.click();
    });

});
t2a7ltrp

t2a7ltrp1#

jQuery在使用 AJAX 请求加载二进制数据时存在一些问题,因为它尚未实现某些HTML5 XHR v2功能,请参阅enhancement requestdiscussion
考虑到这一点,您有两种解决方案之一:

第一个解决方案是放弃JQuery并使用XMLHTTPRequest

使用原生HTMLHTTPRequest,下面是执行所需操作的代码

var req = new XMLHttpRequest();
  req.open("GET", "/file.pdf", true);
  req.responseType = "blob";

  req.onload = function (event) {
    var blob = req.response;
    console.log(blob.size);
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="Dossier_" + new Date() + ".pdf";
    link.click();
  };

  req.send();

第二种解决方案,使用jquery-ajax本机插件

这个插件可以在here中找到,可以用于JQuery中缺少的XHRV 2功能,下面是如何使用它的示例代码

$.ajax({
  dataType: 'native',
  url: "/file.pdf",
  xhrFields: {
    responseType: 'blob'
  },
  success: function(blob){
    console.log(blob.size);
      var link=document.createElement('a');
      link.href=window.URL.createObjectURL(blob);
      link.download="Dossier_" + new Date() + ".pdf";
      link.click();
  }
});
hsvhsicv

hsvhsicv2#

我是新手,大部分的代码是从谷歌搜索。我得到了我的pdf下载与下面的代码(试错播放)工作。感谢代码提示(xhrFields)以上。

$.ajax({
            cache: false,
            type: 'POST',
            url: 'yourURL',
            contentType: false,
            processData: false,
            data: yourdata,
             //xhrFields is what did the trick to read the blob to pdf
            xhrFields: {
                responseType: 'blob'
            },
            success: function (response, status, xhr) {

                var filename = "";                   
                var disposition = xhr.getResponseHeader('Content-Disposition');

                 if (disposition) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                } 
                var linkelem = document.createElement('a');
                try {
                                           var blob = new Blob([response], { type: 'application/octet-stream' });                        

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //   IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) { 
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");

                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.target = "_blank";
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
                    }   

                } catch (ex) {
                    console.log(ex);
                } 
            }
        });
fruv7luv

fruv7luv3#

在html5中你可以很容易地做到这一点:

var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove();
ukqbszuj

ukqbszuj4#

对于那些寻找更现代的方法的人,你可以使用fetch API。下面的例子展示了如何下载一个PDF文件。用下面的代码可以很容易地完成。

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/pdf'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.pdf";
    document.body.appendChild(a);
    a.click();
})

我相信这种方法比其他XMLHttpRequest解决方案更容易理解,而且它的语法与jQuery方法相似,不需要添加任何额外的库。
当然,我建议你检查一下你正在开发的浏览器,因为这种新方法在IE上不起作用。你可以在下面的[链接][1]上找到完整的浏览器兼容性列表。

    • 重要信息**:在本例中,我向侦听给定url的服务器发送了一个JSON请求。必须设置url,在我的示例中,我假设您了解这一部分。另外,考虑请求工作所需的头。由于我发送的是JSON,因此必须添加Content-Type头并将其设置为application/json; charset=utf-8。以便让服务器知道它将接收的请求的类型。
vh0rcniy

vh0rcniy5#

试试这个:

$(document).on('click', '.download-ss-btn', function () {

    $.ajax({
        type: "POST",
        url: 'http://127.0.0.1:8080/utils/json/pdfGen',
        data: {
            data: JSON.stringify(jsonData)
        },
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        }

    }).done(function (data) {
        let binaryString = window.atob(data);
        let binaryLen = binaryString.length;
        let bytes = new Uint8Array(binaryLen);

        for (let i = 0; i < binaryLen; i++) {
            let ascii = binaryString.charCodeAt(i);
            bytes[i] = ascii;
        }
        var blob = new Blob([data], {type: "application/pdf"});
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "Sample.pdf";
        link.click();
    });
});

相关问题