无法加载pdf文档,NodeJs

时间:2016-03-22 20:11:53

标签: angularjs node.js pdf

我正在尝试使用已经存在于模拟测试数据下的pdf,在没有提示的情况下下载pdf。我可以使用下面的代码完成上述任务。但是当我尝试打开下载的pdf时,我收到“无法加载pdf文档”我在这里缺少什么。请帮助。

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

3 个答案:

答案 0 :(得分:1)

你必须使用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);
    });
}

如果您想在下载后保留文件,请替换

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

通过

res.download(filePath, name);
角度应用程序中的

使用$ window.open(url,'_ self');

答案 1 :(得分:0)

这很完美。

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

答案 2 :(得分:0)

如果上述解决方案不能解决您的问题,并且您使用的是 nginx + express,则问题可能出在 nginx 缓冲响应上。您可以使用以下方法禁用它:

proxy_buffering off;
相关问题