How can I download a file that is in my server to my machine accessing a page in a nodeJS server?
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?
Installing Express Use the following command to install express: npm install express --save.
The res. download() function transfers the file at path as an 'attachment'. Typically, browsers will prompt the user to download. Parameters: The filename is the name of the file which is to be downloaded as attachment and fn is a callback function.
Express has a helper for this to make life easier.
app.get('/download', function(req, res){ const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`; res.download(file); // Set disposition and send it. });
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');
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); });
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.
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.
res.download()
It transfers the file at path as an “attachment”. For instance:
var express = require('express'); var router = express.Router(); // ... router.get('/:id/download', function (req, res, next) { var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param var fileName = "report.pdf"; // The default name the browser will use res.download(filePath, fileName); });
res.download()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With