Problem:
How to download files from a file stored in the server, Downloading a file to local machine by accessing a page in Node.js server?
Solution:
Using the helper functions provided by Express.js can simplify this process:
app.get('/download', function(req, res){ const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`; res.download(file); // Set disposition and send it. });
Old solution :
In order for the browser to recognize the file name, you need to use other HTTP header to specify more information:
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
You can also send MIME types, for example:
res.setHeader('Content-type', 'video/quicktime');
The following is a more detailed sample code:
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.getType(file); res.setHeader('Content-disposition', 'attachment; filename=' + filename); res.setHeader('Content-type', mimetype); var filestream = fs.createReadStream(file); filestream.pipe(res); });
Please Note that this example code uses a stream to read the file, which is the preferred asynchronous method in Node.js.
The above is the detailed content of How to Download Files from a Node.js Server Using Express.js?. For more information, please follow other related articles on the PHP Chinese website!