app.post('/asset', function(request, response){
var tempFile="/home/applmgr/Desktop/123456.pdf";
fs.readFile(tempFile, function (err,data){
response.contentType("application/pdf");
response.send(data);
});
});
I am a new bie to expressjs, I can't send the response with the data object. The binary content is visible in the browser. Give me suggestions how to handle this ?
My Solution for sending a PDF directly to the Browser:
app.get('/my/pdf', function (req, res) {
var doc = new Pdf();
doc.text("Hello World", 50, 50);
doc.output( function(pdf) {
res.type('application/pdf');
res.end(pdf, 'binary');
});
});
res.end() with the second param 'binary' did the trick in my case. Otherwise express interpret it as a string
I tested your code and it works for me in chrome with one change:
Change app.post
to app.get
EDIT: since you seem to think a POST-only server is a good idea, read this: http://net.tutsplus.com/tutorials/other/a-beginners-introduction-to-http-and-rest/ Scroll down until the HTTP verbs and check out the difference between GET and POST. :)
Some quick research suggests that other browsers might have other issues, IE for example might expect the URL to end in .pdf
. Since I'm on my Mac I can't test that for you ;)
Specifying how a file download is handled all comes down to the Content-disposition
header. You can also specify the name of the file here as well. We also set the Content-type
to ensure the browser knows what to do with the file given to it.
app.post('/url/to/hit', function(req, res, next) {
var stream = fs.readStream('/location/of/pdf');
var filename = "WhateverFilenameYouWant.pdf";
// Be careful of special characters
filename = encodeURIComponent(filename);
// Ideally this should strip them
res.setHeader('Content-disposition', 'inline; filename="' + filename + '"');
res.setHeader('Content-type', 'application/pdf');
stream.pipe(res);
});
Now if you look more closely at the Content-disposition
, you'll notice the inline;
field is what sets how the browser reacts to the file. If you want to force downloads, you can do so by setting inline;
to attatchment;
I've also found out (by being burnt a couple times), that if you set special characters in your filename, it can break. So I encodeURIComponent()
the filename to ensure that doesn't happen.
Hope that helps others trying to figure out the same!