Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Pdf in browser using express js

I'm trying to serve a PDF via Express in a way it is displayed in browser:

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

However, the browser shows binary content. How to handle this correctly?

like image 649
Dexter Avatar asked Jul 22 '12 06:07

Dexter


People also ask

How do you send a PDF from node Express app to the browser?

contentType("application/pdf"); res. send(data); This should directly send PDF content into the browser. Hope this answers your question.


2 Answers

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.

Express.js Example:

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 attachment;

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!

Edit

In the time between me posting this originally and now, I've found out how to correctly encode the content-disposition's filename parameter. According to the spec, the filename should be RFC5987 encoded. I ended up finding an example code snippet from MDN that correctly handles the encoding here (encodeURIComponent() isn't the entirely correct format for this field).

MDN Snippet

var fileName = 'my file(2).txt'; var header = "Content-Disposition: attachment; filename*=UTF-8''"               + encodeRFC5987ValueChars(fileName);  console.log(header);  // logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"  function encodeRFC5987ValueChars (str) {     return encodeURIComponent(str).         // Note that although RFC3986 reserves "!", RFC5987 does not,         // so we do not need to escape it         replace(/['()]/g, escape). // i.e., %27 %28 %29         replace(/\*/g, '%2A').             // The following are not required for percent-encoding per RFC5987,              // so we can allow for a little better readability over the wire: |`^             replace(/%(?:7C|60|5E)/g, unescape); } 

Another note on top of this one, browsers don't fully comply with the spec either. Some characters will still come back incorrectly from a download (at least when I tested it).

You can get around this problem by updating how your downloads work. If your download URL ends with the filename (and you don't supply a filename attribute in the header), it will correctly get the filename from the URL encoded value. IE 'http://subdomain.domain-url.com/some/path/to/downloads/' + encodeURIComponent("You're there, download this!.pdf")

Jeeze, and all to supply a file name to your downloads!

like image 190
AlbertEngelB Avatar answered Sep 21 '22 22:09

AlbertEngelB


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

like image 22
rdrey Avatar answered Sep 22 '22 22:09

rdrey