37

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?

YakovL
  • 7,557
  • 12
  • 62
  • 102
Dexter
  • 12,172
  • 9
  • 27
  • 30
  • Try `response.end(data)`; express's `send` method might be doing some second-guessing. – ebohlman Jul 22 '12 at 11:28
  • I've added an answer on how to properly set how the browser reacts to the file you are giving to it. You can set these things up in the header, let me know if you have any questions. – AlbertEngelB Feb 14 '14 at 19:59

7 Answers7

40

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.createReadStream('/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!

AlbertEngelB
  • 16,016
  • 15
  • 66
  • 93
  • Just pointing out a typo, it should be "attachment" in the content-disposition header, not "attatchment". – Marcus Nov 30 '16 at 13:19
13

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

rdrey
  • 9,379
  • 4
  • 40
  • 52
  • yes after changing from post to get it is working in my firefox, safari, opera and chrome – Dexter Jul 23 '12 at 09:41
  • So it is not possible with the app.post ? Because I configured the server and maintaining to take only post requests. – Dexter Jul 23 '12 at 09:47
  • 1
    hmm... not sure why you would configure your server to do POST requests only: browser's GET any URL you send them to. That's just how http works. :) POST is usually used for form submissions, or when you use HTTP to create something, not GET it. – rdrey Jul 23 '12 at 11:25
  • @DSK added a link in my answer that will clear this up for you. – rdrey Jul 23 '12 at 11:30
  • 1
    To be fair, there are use cases where you would want to get a PDF in response to a POST. – AlbertEngelB Feb 14 '14 at 19:23
  • 1
    I'm pretty new to Node. What makes this method of serving up a pdf so different from the sendfile(some.html) that I've been using. Can someone explain how this is working and why I don't have to read from the file system for html files? – user137717 Jan 27 '15 at 00:39
  • @rdrey I get a weird warning from this. Firefox says this pdf may not be displayed properly, click here to display somewhere else. The pdf does not display. anyone know why that might be? – user137717 Jan 27 '15 at 01:05
  • @user137717 Probably the content-type header. It gives the browser a hint on how to open the incoming file. – AlbertEngelB Nov 28 '15 at 04:37
  • Yeah, I'd like it if @Dropped.on.Caprica 's comment was marked the accepted answer, it's clearer than mine. – rdrey Dec 02 '15 at 16:06
  • @rdrey Thanks for your vote of confidence! I expanded on my answer a bit as well, to cover the various issues I've found with setting filenames. Hopefully this will help someone else who's trying to supply a PDF download. – AlbertEngelB Dec 02 '15 at 16:39
12

Actually Express already has this feature for sending files. All you need is :

app.get('/sendMePDF', function(req, res) {
  res.sendFile(__dirname + "/static/pdf/Rabbi.pdf");
})

Here the server will send the file "Rabbi.pdf" and it will open in browser like you open pdf in browser. I placed the file in "static" folder but you can place it anywhere, knowing that sendFile() takes as argument the absolute path (not relative one).

Christiaan Westerbeek
  • 10,619
  • 13
  • 64
  • 89
Peco
  • 121
  • 1
  • 2
11

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

st0ne
  • 106
  • 1
  • 9
sja
  • 2,064
  • 2
  • 18
  • 22
6

It is as simple as following code:

var express = require('express'),
    fs = require('fs'),
    app = express();

app.get('/', function (req, res) {
    var filePath = "/files/my_pdf_file.pdf";

    fs.readFile(__dirname + filePath , function (err,data){
        res.contentType("application/pdf");
        res.send(data);
    });
});

app.listen(3000, function(){
    console.log('Listening on 3000');
});

For complete repo:

Clone node-cheat pdf_browser, run node app followed by npm install express.

Happy Helping!

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
1

According to Express js documentation you can set the Content Type and the Content Disposition all in one function as shown below

 fs.readFile(filePath, (err, data) => {
res.set({
  "Content-Type": "application/pdf", //here you set the content type to pdf
  "Content-Disposition": "inline; filename=" + fileName, //if you change from inline to attachment if forces the file to download but inline displays the file on the browser
});
res.send(data); // here we send the pdf file to the browser
});
Chinelo
  • 45
  • 1
  • 1
  • 10
0
post('/fileToSend/', async (req, res) => {

  const documentPath = path.join(
    __dirname,
    '../assets/documents/document.pdf'
  );
    
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'attachment; filename=document.pdf');

  return res.download(documentPath);
});
Leon Matota
  • 332
  • 5
  • 8