-->

How to send a downloadable pdf to javascript clien

2019-07-29 22:08发布

问题:

I am working on a project where a pdf is dynamically created at the node server and needs to be sent to the javascript client where it should open a download prompt on the browser.

I have created the pdf but sending it and receiving it as downloadable is being troublesome.

Following is the code that I have used at the node to send the pdf but it doesn't seems to be right:

    var pdf = fs.readFile("createdPdf/" + uname + "_44.pdf", function() {
        if (pdf == null) {
            res.writeHead(401, {"Content-Type": "text/html"});
            res.write('Failed');
            res.end();  
            return;
        } else {
            res.writeHead(200, {
                "Content-Type": "text/html"
            });
            res.write(pdf);
            res.end();
        }
    });

And I have no idea how to catch this pdf at the javascript client to open the download prompt.

Currently all other responses from the node are being collected as:

var resp_json = printRequest.getResponseJson();

or

var resp_json = printRequest.getResponseText();

Can anyone help me?

P.S. I am using google closure library at the client (don't ask why, company MO).

Thanx in advance!!

回答1:

Try adding the Content-Disposition: attachment header, like this:

Content-Disposition: attachment; filename="thePdf.pdf"