从ajax响应中下载pdf文件 [英] Download pdf file from ajax response

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

问题描述

我正在尝试让浏览器下载从ajax响应中收到的pdf文件。

I'm trying to make the browser download a pdf file received from an ajax response.

下载pdf文件的启发使用jquery ajax 我模拟这样的点击/下载事件:

Inspired by Download pdf file using jquery ajax I simulate a click/download event like this:

    var req = new XMLHttpRequest();
    req.open("POST", "/servicepath/Method?ids=" + ids, true);
    req.responseType = "blob";
    req.onreadystatechange = function () {
        if (req.readyState === 4 && req.status === 200) {
            var blob = req.response;
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "PdfName-" + new Date().getTime() + ".pdf";
            link.click();
        }
    };
    req.send();

不幸的是,这仅适用于Chrome,但不适用于Firefox + IE。当我尝试在最后两个浏览器中触发它时没有任何反应。

Unfortunately this only works in Chrome, but not Firefox + IE. Nothing happens when I try to trigger it in the last two browsers.

由于CMS的继承,脚本和标记放在iframe中,但我不确定它是否有任何影响a。

The script and markup is placed inside an iframe due to inheritance from an CMS, but I'm not sure if that has any influence a.

如何为所有现代浏览器优化它?

推荐答案


如何为所有现代浏览器优化它?

Any idea on how to optimize it for all modern browsers?

是的,我可以给您使用IE11,Firefox 47和Chrome 52在Windows 10上测试了一个解决方案。目前Microsoft Edge没有任何内容。

Yes, I can give you a solution tested on windows 10 with IE11, Firefox 47 and Chrome 52. Nothing for Microsoft Edge at the moment.

一开始你需要区分你是否在IE或其他两个浏览器。这是因为在IE11上你可以使用:

At the beginning you need to distinguish if you are on IE or the other two browsers. This because on IE11 you can use:

window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");

对于其他两个浏览器,您的代码适用于Chrome但不适用于Firefox,因为您没有附加元素到文档正文。

For the other two browsers your code works on Chrome but not on Firefox because you did not append the element to the document body.

所以更正的代码是:

var req = new XMLHttpRequest();
req.open("POST", "/servicepath/Method?ids=" + ids, true);
req.responseType = "blob";
req.onreadystatechange = function () {
  if (req.readyState === 4 && req.status === 200) {

    // test for IE

    if (typeof window.navigator.msSaveBlob === 'function') {
      window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");
    } else {
      var blob = req.response;
      var link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = "PdfName-" + new Date().getTime() + ".pdf";

      // append the link to the document body

      document.body.appendChild(link);

      link.click();
    }
  }
};
req.send();

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

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