【问题标题】:Send file back after GET request Node.jsGET请求Node.js后发回文件
【发布时间】:2017-04-23 22:36:22
【问题描述】:

我正在尝试使用 MEAN 堆栈构建 REST API,但遇到了问题。我正在将 POST 请求中发送的 .txt 文件保存到服务器,并使用 multer 将其保存在 /uploads 文件夹中。然后我将 req.file 信息保存在 mongodb 的集合中(包括路径)。

我现在遇到的问题是我希望能够使用 ObjectId 处理对该特定文件的 GET 请求。但是我希望能够从文件路径中获取文件,然后将其发送给发出 GET 请求的用户。

现在我只返回与传递的 ObjectId 对应的信息,而不是文件。如何将整个 .txt 文件发回给用户?

exports.findById = function(req, res) {
try
{
    var id = new require('mongodb').ObjectID(req.params.id);
    console.log('Retrieving log: ' + id);

    db.collection('logs', function(err, collection) {
        if(err)
        {
            console.log(err);
        }
        else
        {
            collection.findOne({'_id':id}, function(err, item) {
                if (err) {
                    console.log('Error finding log: ' + err);
                    res.send({'error':'An error has occurred'});
                } else {
                    console.log('' + item + ' found log');
                    console.log(item.path);
                    var file = __dirname + item.path;
                    res.download(file);
                    //res.send(item);
                }
            });
        }
    });
}
catch (e)
{
    console.log('Id passed not correct');
    res.send({'error':'Id passed not correct'});
}

};

【问题讨论】:

    标签: node.js mongodb api mean-stack multer


    【解决方案1】:

    最后我终于让服务器响应了 GET 请求。

    我必须找到已保存到数据库中的文件的文件路径。

    collection.findOne({'_id':id}, function(err, item) {
                    if (err) 
                    {
                        console.log('Error finding log: ' + err);
                        res.send({'error':'An error has occurred'});
                    }
                    if (item)
                    {
                        //Create the path of the file wanted
                        filepath = path.join(__dirname, "../uploads", path.normalize(item.filename));
                        //Send file with the joined file path
                        res.sendFile(filepath);
                    } 
                    else 
                    {
                        console.log("Could not find entry");
                        res.send({'error':'No match found'});
                    }
                });
    

    这使我能够通过获取文件的完整路径将文件发回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-07
      • 2019-11-11
      • 2014-08-10
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      相关资源
      最近更新 更多