0

I am trying to download a pdf without prompt using the pdf which is already present under mocked test data. And I am able to do the above task using the below code.But when I try to open the downloaded pdf I am getting 'Failed to load pdf document' what am I missing here.Kindly help.

fs.readFile('./src/test-data/service/print/notes.pdf', function(error, content) {
    if (error) {
        res.writeHead(500);
        res.end();
    }
    else {
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename=notes.pdf'
        });
        res.end(content, 'utf-8');
    }
});
Raphael
  • 1,738
  • 2
  • 27
  • 47

3 Answers3

1

you must use res.download

function fileExist(fullpath) {
    try {
        return fs.statSync(fullpath).isFile();
    } catch (e) {
        return false;
    }
 }


var name = 'notes.pdf';
var filePath = './src/test-data/service/print/' + name;
if (!Files.Exist(filePath)) {
    console.log("file does't exist");
} else {
    res.download(filePath, name, function(err) {
        fs.unlink(filePath);
    });
}

if you want keep your file after download replace the line

res.download(filePath, name, function(err) {
    fs.unlink(filePath);
});

by

res.download(filePath, name);

in the angular application use $window.open(url, '_self');

  • I am getting "ReferenceError: Files is not defined" in my app.Thanks for the ans.I found another way. – Raphael Mar 23 '16 at 04:18
0

This is working perfectly.

var file = fs.createReadStream('./src/test-data/service/print/notes.pdf');
var stat = fs.statSync('./src/test-data/service/print/notes.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=agreement.pdf');
file.pipe(res);
Raphael
  • 1,738
  • 2
  • 27
  • 47
0

If the above solutions do not solve your problem, and your using nginx + express, the problem might be with nginx buffering the response. You can disable that using the following:

proxy_buffering off;
aosaimy
  • 541
  • 4
  • 3