Update(更新资料)
Express has a helper for this to make life easier.
(Express为此提供了一个帮助 ,使生活更轻松。)
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
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.
(就您的浏览器而言,该文件的名称仅为“下载”,因此您需要使用另一个HTTP标头为其提供更多信息。)
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
You may also want to send a mime-type such as this:
(您可能还希望发送如下的mime类型:)
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);
});
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.(在这种情况下,我使用的是mime类型的库-node-mime ,以检查文件的mime类型。)
Another important thing to note here is that I have changed your code to use a readStream.
(这里要注意的另一件事是,我已将您的代码更改为使用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.(这是一种更好的处理方式,因为名称中的任何带有“ Sync”的方法都被禁止使用,因为node是异步的。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…