GET 请求后发回文件 Node.js

Send file back after GET request Node.js

我正在尝试使用 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'});
}

};

最后终于让服务器响应了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'});
                }
            });

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