NodeJS sendFile with File Name in download

落花浮王杯 提交于 2020-02-19 10:47:13

问题


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


回答1:


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");
});



回答2:


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




回答3:


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 ?

  1. http://yourapi.com/get/file1.dat
  2. 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')
});


来源:https://stackoverflow.com/questions/41941724/nodejs-sendfile-with-file-name-in-download

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!