我对nodejs
有问题。我现在正在制作一个服务器,该服务器将提供用户请求的文件。我做了什么:
- 我明白了路径
- 查找文件 (
fs.exists()
) - 如果路径是文件,则获取流
- 流管道(响应)
现在的问题是我希望用户下载文件,但是如果我写一个.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()
}
好吧,在您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功能在内部所做的,所以这个功能可能也值得一看。
好吧,看起来问题是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