使用jquery ajax下载pdf文件

时间:2021-08-06 00:31:29

I want to download a pdf file for jquery ajax response. Ajax response contains pdf file data. I tried this solution. My code is given below but I always get a blank pdf.

我想下载一个用于jquery ajax响应的pdf文件。Ajax响应包含pdf文件数据。我试着这个解决方案。我的代码在下面给出,但我总是得到一个空白的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();
    });


});

2 个解决方案

#1


39  

jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion

jQuery在使用AJAX请求加载二进制数据时遇到了一些问题,因为它还没有实现HTML5 XHR v2功能,请参见这个增强请求和讨论

Given that, you have one of two solutions:

鉴于此,您有两种解决方案:

First solution, abandon JQuery and use XMLHTTPRequest

首先,放弃JQuery并使用XMLHTTPRequest。

Go with the native HTMLHTTPRequest, here is the code to do what you need

使用原生的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();

Second solution, use the jquery-ajax-native plugin

第二种解决方案是使用jquery-ajax-native插件

The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it

这个插件可以在这里找到,并且可以用于JQuery中缺少的XHR V2功能,下面是如何使用它的示例代码

$.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();
  }
});

#2


5  

I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.

我是新手,大部分代码来自谷歌搜索。我用下面的代码下载了我的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);
                } 
            }
        });

#1


39  

jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion

jQuery在使用AJAX请求加载二进制数据时遇到了一些问题,因为它还没有实现HTML5 XHR v2功能,请参见这个增强请求和讨论

Given that, you have one of two solutions:

鉴于此,您有两种解决方案:

First solution, abandon JQuery and use XMLHTTPRequest

首先,放弃JQuery并使用XMLHTTPRequest。

Go with the native HTMLHTTPRequest, here is the code to do what you need

使用原生的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();

Second solution, use the jquery-ajax-native plugin

第二种解决方案是使用jquery-ajax-native插件

The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it

这个插件可以在这里找到,并且可以用于JQuery中缺少的XHR V2功能,下面是如何使用它的示例代码

$.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();
  }
});

#2


5  

I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.

我是新手,大部分代码来自谷歌搜索。我用下面的代码下载了我的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);
                } 
            }
        });