NodeJS sendFile with File Name in download
This is my solution:
var fs = require('fs');
var path = require('path');
const transfer = exports;
transfer.responseFile = function (basePath, fileName, res) {
var fullFileName = path.join(basePath, fileName);
fs.exists(fullFileName, function (exist) {
if (exist) {
var filename = path.basename(fullFileName);
res.setHeader('Content-Disposition', 'attachment; filename=' + filename);
res.setHeader('Content-Transfer-Encoding', 'binary');
res.setHeader('Content-Type', 'application/octet-stream');
res.sendFile(fullFileName)
} else {
res.sendStatus(404);
}
});
};
and use it:
router.get('/myfile', function (req, res) {
transfer.responseFile("/var/nodejs", 'fileToDownload.dat', res);
});
Thank you to all helpers :)
there is a specialized method res.download
which covers all for you ;)
router.get('/get/myfile', function (req, res) {
res.download("/file_in_filesystem.dat", "name_in_browsers_downloads.dat");
});
If you have multiple routes like below: "/get/myfile1", "/get/myfile2", "/get/myfile
Why don't you make a generic one. which can handle all request and it will solve your link(download_name) problem too. You can do it as below
router.get('/get/:fileName',function(req,res){
res.sendFile('/file_path/'+req.params.fileName)
});
Edit After Comment (EDIT 1):
Sorry, i didn't get your point. I am assuming that if you are developing the backend api, you should have the control of choosing the url too, right ?
Giving an example:
when server side is this:
router.get('/get/:fileName',function(req,res){
res.sendFile('/file_path/'+req.params.fileName)
});
Based on your posted code and implementation. The files which need to get downloaded are finite in number and known files.
assuming there are 2 files : "file1.dat" and "file2.dat"
you can call the api as below right ?
- http://yourapi.com/get/file1.dat
- http://yourapi.com/get/file2.dat
am i missing something ?
EDIT 2:
If that is the case, i think this would solve your problem, instead of using sendFile use res.attachment:
app.get('/get/myfile',function(req,res){
res.attachment('/file.txt');
res.end('Downloaded', 'UTF-8')
});