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 a pdf at the node and streams the pdf back to the client via 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 trouble at how to receive this response back at the javascript client so that a download prompt will open to allow the user to download and save the pdf file.
Please help!
Thanx in advance!
P.S. Plz also suggest any better way to implement my node's code(if there is any)
Edit: One possible solution would be to send my request like this:
window.location.assign('/node/download');
This way i get the download prompt and everything works fine except that the asynchronous nature of the product is sacrificed. Is there a work around for this so that I can also retain asynchronicity?
I implement similar async file generation features in some apps. The approach I take is a little more involved, but keeps your interface async.
This is invisible to the user, they will just need to wait for the second transaction to come back.
For downloading a pdf file saved on the server
Make the request like this from the client javascript:
At the node handle the request received from above and respond: