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

查看:39
本文介绍了使用 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天全站免登陆