Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS sendFile with File Name in download

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".

like image 813
Massimo Caroccia Avatar asked Jan 30 '17 17:01

Massimo Caroccia


People also ask

How do I download a file from node js server?

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.

How do I download a text file in node?

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.

What is __ Dirname Nodejs?

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.


2 Answers

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");
});
like image 107
Michal Miky Jankovský Avatar answered Sep 17 '22 20:09

Michal Miky Jankovský


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 :)

like image 27
Massimo Caroccia Avatar answered Sep 18 '22 20:09

Massimo Caroccia