使用express js在浏览器中显示Pdf

Dex*_*ter 27 javascript pdf buffer node.js express

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

我是表达js的新bie,我不能用数据对象发送响应.二进制内容在浏览器中可见.给我建议如何处理这个?

Alb*_*elB 28

指定如何处理文件下载都归结为Content-disposition标题.您也可以在此处指定文件的名称.我们还设置了Content-type以确保浏览器知道如何处理给它的文件.

Express.js示例:

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);
});
Run Code Online (Sandbox Code Playgroud)

现在,如果你仔细观察Content-disposition,你会注意到该inline;字段设置了浏览器对文件的反应.如果要强制下载,可以通过设置inline;attachment;

我也发现(被烧了几次),如果你在你的文件名中设置特殊字符,它就会破坏.所以我encodeURIComponent()的文件名确保不会发生.

希望能帮助其他人试图找出相同的东西!

编辑

在我最初和现在发布之间的时间里,我已经找到了如何正确编码content-disposition的文件名参数. 根据规范,文件名应为RFC5987编码. 我最终从MDN中找到了一个示例代码片段,它正确地处理了这里的编码(encodeURIComponent()这个字段的格式不完全正确).

MDN代码段

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);
}
Run Code Online (Sandbox Code Playgroud)

除此之外的另一个注意事项,浏览器也不完全符合规范.某些字符仍然会从下载中错误地返回(至少在我测试时).

您可以通过更新下载的工作方式来解决问题.如果您的下载URL以文件名结尾(并且您没有filename在标头中提供属性),它将从URL编码值正确获取文件名.IE'http://subdomain.domain-url.com/some/path/to/downloads/' + encodeURIComponent("You're there, download this!.pdf")

Jeeze,以及为您的下载提供文件名的所有内容!


sja*_*sja 10

我将PDF直接发送到浏览器的解决方案:

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');
    });
});
Run Code Online (Sandbox Code Playgroud)

使用第二个参数'binary'的res.end()在我的情况下完成了这个技巧.否则表达将其解释为字符串

  • 现在不推荐使用`doc.output`方法. (3认同)

小智 10

其实Express已经有这个发送文件的功能了。所有你需要的是 :

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

在这里,服务器将发送文件“Rabbi.pdf”,它会像在浏览器中打开 pdf 一样在浏览器中打开。我将文件放在“静态”文件夹中,但您可以将它放在任何地方,因为知道 sendFile() 将绝对路径(不是相对路径)作为参数。


rdr*_*rey 9

我测试了你的代码,它适用于我的chrome,只有一个改变:app.post改为app.get

编辑:因为您似乎认为只有POST的服务器是个好主意,请阅读:http://net.tutsplus.com/tutorials/other/a-beginners-introduction-to-http-and-rest/ 向下滚动直到HTTP动词并检查GET和POST之间的区别.:)

一些快速研究表明,其他浏览器可能有其他问题,例如IE可能希望URL结束.pdf.因为我在我的Mac上我不能为你测试;)


Zee*_*mon 6

它就像下面的代码一样简单:

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');
});
Run Code Online (Sandbox Code Playgroud)

对于完整的回购

克隆节点作弊pdf_browsernode app然后运行npm install express.

乐于助人!