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

问题描述

如何将服务器中的文件下载到访问 nodeJS 服务器中的页面的机器上?

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?

推荐答案

更新

Express 有一个帮手,让生活更轻松.

app.get('/download', function(req, res){
  const 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');
var fs = require('fs');

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.这是一种更好的处理方式,因为使用名称中带有 'Sync' 的任何方法都是不受欢迎的,因为 node 是异步的.

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 服务器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:15