使用Express从NodeJS Server下载文件 [英] Download a file from NodeJS Server using Express

查看:407
本文介绍了使用Express从NodeJS Server下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个愚蠢的问题,但是如何将我的服务器中的文件下载到我的机器访问nodeJS服务器中的页面?

Probably a dumb question but how can I download a file that is in my server to my machine accessing a page in a nodeJS server?

我正在使用ExpressJS和我一直在尝试:

I'm using the ExpressJS and I've been trying this:

app.get('/download', function(req, res){

  var file = fs.readFileSync(__dirname + '/upload-folder/dramaticpenguin.MOV', 'binary');

  res.setHeader('Content-Length', file.length);
  res.write(file, 'binary');
  res.end();
});

但是我无法获取文件名和文件类型(或扩展名)。有人可以帮我吗?

But I can't get the file name and the file type ( or extension ). Can anyone help me with that?

非常感谢

推荐答案

更新



快速有一个帮助使生活更轻松。

app.get('/download', function(req, res){
  var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
  res.download(file); // Set disposition and send it.
});



旧答案



至于你浏览器关心的是,该文件的名称只是下载,因此您需要通过使用另一个HTTP标头来提供更多信息。

Old Answer

As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.

res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');

您可能还想发送一个mime类型,如:

You may also want to send a mime-type such as this:

res.setHeader('Content-type', 'video/quicktime');

如果你想要更深入的东西,那么你可以去。

If you want something more in-depth, here ya go.

var path = require('path');
var mime = require('mime');

app.get('/download', function(req, res){

  var file = __dirname + '/upload-folder/dramaticpenguin.MOV';

  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);
});

您可以将头值设置为任何您喜欢的值。在这种情况下,我正在使用一个mime类型的库 - node-mime 来检查这个文件的MIME类型是。

You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.

这里要注意的另一个重要的事情是我已经改变了你的代码来使用一个readStream。这是一个更好的方式来做事情,因为使用名称中的同步的任何方法被皱眉了,因为节点是异步的。

Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.

这篇关于使用Express从NodeJS Server下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆