1

我有一个问题nodejs。我现在正在制作一个服务器,它将为用户请求的文件提供服务。我做了什么:

  • 我得到了路径
  • 找到文件 ( fs.exists())
  • 如果路径是文件获取流
  • stream.pipe (响应)

现在的问题是我希望用户下载文件,但是如果我写一个 .txt 文件,管道方法会在浏览器中写入文件的内容......所以,我尝试使用 .pdf,但是在这个万一网页继续加载,没有任何反应......有人可以帮忙吗?

if(exists) {

        response.writeHead(302, {"Content-type":'text/plain'});

        var stat = fs.statSync(pathname);

        if(stat.isFile()) {
            var stream = fs.createReadStream(pathname);
            stream.pipe(response);
        } else {
            response.writeHead(404, {"Content-type":'text/plain'});
            response.end()
        }


        //response.end();

} else {
        response.writeHead(404, {"Content-type":'text/plain'});
        response.write("Not Found");
        response.end()
}
4

2 回答 2

1

好吧,看起来问题是 pdf 内容类型不是text/plain

将内容类型替换为application/pdf

喜欢:

response.writeHead(302, {"Content-type":'application/pdf'});

更多信息: http ://www.iana.org/assignments/media-types和http://www.rfc-editor.org/rfc/rfc3778.txt

于 2013-10-25T13:11:44.233 回答
1

好吧,在您的if情况下,您总是将Content-Type标题设置为text/plain,这就是您的浏览器内联显示您的文本文件的原因。而对于您的 PDF,text/plain它应该是错误的application/pdf,因此您需要动态设置类型。

如果您希望浏览器强制下载,请设置以下标头:

Content-Disposition: attachment; filename="your filename…"
Content-Type: text/plain (or whatever your content-type is…)

基本上,这就是Express 的 res.download函数在内部所做的,所以这个函数可能也值得一看。

于 2013-10-25T13:09:52.510 回答