How to download a pdf file through javascript?

My javascript code makes the following AJAX request to my node.js server:

var url = '/node/download';
var downloadRequest = new goog.net.XhrIo();
downloadRequest.headers.set('content-type', 'application/json');
downloadRequest.send(url);

My node.js server creates pdf in node and passes the PDF back to the client using the following code:

    var filestream = fs.createReadStream(pdfpath);                  
    res.writeHead(200, {
        'Content-disposition': 'attachment; filename=' + filename,
        "Content-Type":"application/pdf","Content-Transfer-Encoding": "binary"});
    filestream.on('data', function(chunk) {                     
        res.write(chunk);
    });
    filestream.on('end', function() {
        res.end();
    });

But now I am having problems with how to get this answer back on the javascript client to open a download prompt so that the user can download and save the file in pdf format.

Please, help!

Thanx in advance!

PS Plz also offers a better way to implement my node code (if any)

Edit: One possible solution is to send my request as follows:

window.location.assign('/node/download');

This way I get a download prompt and everything works fine, except that the asynchronous nature of the product is sacrificed. Is there any work for this so that I can maintain asynchrony?

+1
2

PDF,

, , javascript :

var reqObj = new XMLHttpRequest();
reqObj.open('GET','getpdf',true);     // 'getpdf' is the URI to recongize your request at the server
reqObj.send();

reqObj.onreadystatechange = function() {
    var resObj = this;
    if(resObj.readyState == resObj.DONE) {
        if (resObj.status != 200) {
            console.log("pdf can't be downloaded");
        } else if (resObj.status == 200){
            var resTxt = reqObj.responseText;
            window.location.assign(resTxt);    // Opens the pdf download prompt
        }
    }
}

node , , :

var http = require('http');

function getPDFUrl() {
    return "http://testing.com/pdf/test.pdf";
}

var handler = http.createServer(function(request, response) {
if (request.url == 'getpdf' && request.method.toLowerCase() == 'get') {
    var pdfUrl = getPDFUrl();       //get pdf url here

    if (pdfUrl != null && pdfUrl != undefined && pdfUrl != '') {
        response.writeHead(200, {"Content-Type":"text/html"});
        response.write(pdfUrl);
        response.end();
    } else {
        response.writeHead(404, {"Content-Type":"text/html"});
        response.write("Not Found");
        response.end();
    }

}
});
+1

async . , , , .

  • .
  • URL- .
  • .

, .

0

Source: https://habr.com/ru/post/1568239/


All Articles