Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

javascript - Download pdf file from ajax response

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

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...