从ajax响应下载pdf文件

时间:2022-01-03 09:52:34

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

我试图让浏览器下载从ajax响应接收的pdf文件。

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

受到使用jquery ajax下载pdf文件的启发,我模拟了如下的单击/下载事件:

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

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

不幸的是,这只适用于Chrome,而不适用于Firefox + IE。当我尝试在最后两个浏览器中触发它时,什么都不会发生。

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.

脚本和标记被放置在一个iframe中,这是由于从CMS中继承而来的,但是我不确定这是否有任何影响。

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

关于如何优化所有现代浏览器的想法?

2 个解决方案

#1


12  

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

关于如何优化所有现代浏览器的想法?

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.

是的,我可以给你一个在windows 10上测试IE11,火狐47和Chrome 52的解决方案。微软目前没有任何优势。

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

在开始的时候,你需要区分你是在IE还是其他两个浏览器上。这是因为在IE11上你可以使用:

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

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.

对于其他两个浏览器,您的代码可以在Chrome上工作,但不能在Firefox上工作,因为您没有将元素添加到文档主体。

So the corrected code is:

所以修正后的代码是:

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

#2


14  

This version will work in all modern browsers:

本版本将适用于所有现代浏览器:

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 filename = "PdfName-" + new Date().getTime() + ".pdf";
        if (typeof window.chrome !== 'undefined') {
            // Chrome version
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(req.response);
            link.download = "PdfName-" + new Date().getTime() + ".pdf";
            link.click();
        } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE version
            var blob = new Blob([req.response], { type: 'application/pdf' });
            window.navigator.msSaveBlob(blob, filename);
        } else {
            // Firefox version
            var file = new File([req.response], filename, { type: 'application/force-download' });
            window.open(URL.createObjectURL(file));
        }
    }
};
req.send();

I was trying to get also a version for safari but it didn't work so well. Will try to keep investigate it and give a solution for that too.

我也试着得到safari的版本,但效果不太好。我会继续调查,并给出解决办法。

#1


12  

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

关于如何优化所有现代浏览器的想法?

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.

是的,我可以给你一个在windows 10上测试IE11,火狐47和Chrome 52的解决方案。微软目前没有任何优势。

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

在开始的时候,你需要区分你是在IE还是其他两个浏览器上。这是因为在IE11上你可以使用:

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

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.

对于其他两个浏览器,您的代码可以在Chrome上工作,但不能在Firefox上工作,因为您没有将元素添加到文档主体。

So the corrected code is:

所以修正后的代码是:

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

#2


14  

This version will work in all modern browsers:

本版本将适用于所有现代浏览器:

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 filename = "PdfName-" + new Date().getTime() + ".pdf";
        if (typeof window.chrome !== 'undefined') {
            // Chrome version
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(req.response);
            link.download = "PdfName-" + new Date().getTime() + ".pdf";
            link.click();
        } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE version
            var blob = new Blob([req.response], { type: 'application/pdf' });
            window.navigator.msSaveBlob(blob, filename);
        } else {
            // Firefox version
            var file = new File([req.response], filename, { type: 'application/force-download' });
            window.open(URL.createObjectURL(file));
        }
    }
};
req.send();

I was trying to get also a version for safari but it didn't work so well. Will try to keep investigate it and give a solution for that too.

我也试着得到safari的版本,但效果不太好。我会继续调查,并给出解决办法。