I try to send file to client with this code:
router.get('/get/myfile', function (req, res, next) {
res.sendFile("/other_file_name.dat");
});
it's work fine but I need that when user download this file from the url:
http://mynodejssite.com/get/myfile
the filename into the browser must be "other_file_name.dat" and not "myfile".
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.
Method 1: Using 'https' and 'fs' module We can use the http GET method to fetch the files that are to be downloaded. The createWriteStream() method from fs module creates a writable stream and receives the argument with the location of the file where it needs to be saved.
The __dirname in a node script returns the path of the folder where the current JavaScript file resides. __filename and __dirname are used to get the filename and directory name of the currently executing file. The ./ gives the current working directory. It works similar to process. cwd() method.
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");
});
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 :)
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