即时更改文件名以供下载

时间:2014-04-03 08:35:48

标签: node.js express download static-files

我通过将其原始名称重命名为userID + '_' + new Date().getTime() + fileExt来保存用户上传。我将文件属性存储在mongodb集合中:

{
name : String //generated name
, originalName : String //its original name
...
}

现在,当用户请求下载文件时,我必须向用户提供文件的原始名称(在db中保留,因此没有问题)。

对于以下请求

GET /users/:userId/uploads/:fileId?type=download

我有这个处理程序

//the mongoose query
UserUpload.findById(req.params.fileId).exec(function(err, doc){
 var fileLocation = __dirname + '/public/uploads/users/' + req.params.userId + '/' + doc.name;

 if(req.query.type && req.query.type == 'download') {
   // I don't know what should I do now
   // Downloader.download(fileLocation, newName);
 } 

 });

我阅读了wikinode-static module但是无法弄清楚如何做这项工作?

2 个答案:

答案 0 :(得分:11)

我在这里找到答案:Download a file from NodeJS Server using Express。使用快递和不使用快递。

如果您使用Express,这太简单了。以下是res.download的文档。我无法相信解决方案只是一行代码:

res.download('/path/to/file.ext', 'newname.ext');

答案 1 :(得分:0)

这是我在我的一个项目中使用的,smil是我需要下载的一种文件,没关系。 在该项目中,我将DOWNLOAD_DIR作为全局变量,其中包含下载文件夹的完整路径。

这可能会让很多人感到畏缩(特别是fileExistSync),但这只是一个开始。

var DOWNLOAD_DIR = '/path/to/download',
url = require('url'),
http = require('http'),


/*
download
IN_:
            file_url,       url of the file to download
OUT:
            file_name,  full path to downloaded file, null if the file cound t be downloaded.
    COM:
        download a file, the file name will be the last part of the url (http://why.so/serious.txt => serious.txt).
            WARNING: Do NOT follow redirections.
*/
function download(file_url, callback) {
    var options = {host: url.parse(file_url).host, port: 80, path: url.parse(file_url).pathname},
        file_name = url.parse(file_url).pathname.split('/').pop(),
    //Creating the file
        file = fs.createWriteStream(DOWNLOAD_DIR + file_name, {flags: 'w', encoding: 'binary'});

    console.log('Downloading file from ' + file_url);
    console.log('\tto ' + file_name);
    http.get(options, function (res) {
        res.pipe(file, {end: 'false'});
        //When the file is complete
        res.on('end', function () {
            //Closing the file
            file.end();
            console.log('\t\tDownloaded '+ file_name);
            callback(DOWNLOAD_DIR + file_name);
        });
    });

    process.on('uncaughtException', function(err) {
        console.log('Can t download ' + file_url + '\t(' + err + ')', false);
        callback(null);
    });
}


/*
download_smil
    IN_:
        file_url,       url of the file to download
    OUT:
        file_name,  full path to downloaded file
    COM:
        Follow http redirection and then call download function to download it.
            You can modify the cad function to use custom names.
*/
function download_smil(file_url, callback) {
    function cad(link, callback) {
        //Does the file already exist?
        var file = url.parse(link).pathname.substr(url.parse(link).pathname.lastIndexOf('/') + 1),
            pkmn;
        pkmn = fs.existsSync(DOWNLOAD_DIR + '/' + file);
        if (pkmn) {
            //YES: callback
            console.log('File ' + file + ' already exist, skipping');
            callback(DOWNLOAD_DIR + file, true);
        } else {
            //NO: Download it
            console.log('Will download ' + link);
            download(link, callback);
        }
    }
    //GET the page
    http.get(file_url, function (res) {
        var link;
        //console.log('res.statusCode = ' + res.statusCode + ' res.headers.location = ' + res.headers.location);
        //Check if it is a redirect
        if (res.statusCode > 300 && res.statusCode < 400 && res.headers.location) {
            //console.log('redirect');
            //Check if the hostname is in the location
            if (url.parse(res.headers.location).hostname) {
                //console.log('The link to the smil is res.headers.location');
                link = res.headers.location;
                cad(link, callback);
            } else {
                //console.log('The link to the smil is url_parse(file_url).hostname + res.headers.location = ' + url_parse(file_url).hostname + res.headers.location);
                link = url_parse(file_url).hostname + res.headers.location;
                cad(link, callback);
            }
        } else {
            //console.log('The url is good : ' + file_url);
            cad(file_url, callback);
        }
    });
}
相关问题