使用jquery ajax下载pdf文件 [英] Download pdf file using jquery ajax

查看:161
本文介绍了使用jquery ajax下载pdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为jquery ajax响应下载pdf文件。 Ajax响应包含pdf文件数据。我尝试了这个解决方案。我的代码如下所示,但我总是得到一个空白的pdf。

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.

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


});


推荐答案

jQuery在使用AJAX请求加载二进制数据时遇到一些问题,因为它尚未实现某些HTML5 XHR v2功能,请参阅此增强请求和此讨论

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

鉴于此,您有以下两种解决方案之一:

Given that, you have one of two solutions:

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

使用原生HTMLHTTPRequest,这里是代码做你需要的东西

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

  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-native插件

该插件可在此处找到并可用于JQuery中缺少XHR V2功能,下面是一个如何使用它的示例代码

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

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

这篇关于使用jquery ajax下载pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆