Nodejs写入文件

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

  • 我得到的path
  • find文件( fs.exists()
  • 如果path是一个文件获取stream
  • stream.pipe(响应)

现在的问题是我希望用户下载文件,但是如果我写一个.txt文件,pipe道方法在浏览器中写入文件的内容…所以,我尝试了一个.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() } 

那么,在你的情况下,你总是将Content-Type标题设置为text/plain ,这就是为什么你的浏览器显示你的文本文件内联。 而对于你的PDF, text/plain只是错误的,应该是application/pdf ,所以你需要dynamic设置types。

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

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

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

好吧,看起来问题是,PDF内容types不是text/plain

将内容typesreplace为application/pdf

喜欢:

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

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