使用Express将文件上传保存到Mongo DB

Tre*_*zel 5 file-upload mongodb node.js express

本教程之后,我设法创建了一个带有file输入的表单,该表单将文件上载到指定的目录.这是花花公子和所有,但它没有保存任何东西到数据库,我没有任何参考上传到Jade模板中显示的文件.

这是我正在做的事情:

// add new bulletin
exports.addbulletin = function(db) {
    return function(req, res) {

        var tmp_path = req.files.coverimage.path;
        // set where the file should actually exists - in this case it is in the "images" directory
        var target_path = './public/uploads/' + req.files.coverimage.name;
        // move the file from the temporary location to the intended location
        fs.rename(tmp_path, target_path, function(err) {
            if (err) throw err;
            // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
            fs.unlink(tmp_path, function() {
                if (err) throw err;
                res.send('File uploaded to: ' + target_path + ' - ' + req.files.coverimage.size + ' bytes');
            });
        });

        // Submit to the DB
        collection.insert(req.body, function (err, data) {
            if (err) {
                res.send("There was a problem adding the information to the database.");
            }
            else {
                res.location("index");
                res.redirect("/");
            }
        });

    }
};
Run Code Online (Sandbox Code Playgroud)

第二部分是将req.body(非文件输入的其他表单字段)插入Mongo数据库.我想直接req.files插入它的位置req.body,但这不起作用.

我想,我的困惑在于Mongo的工作方式.我不是数据库专家,但是当你"上传"一个图像时,实际的图像文件应该转到数据库,还是只应该添加一个引用(如图像名称和应用程序中的位置)?

总而言之,我只想将上传的图像(或对它的引用)保存到Mongo数据库,以便我可以在Jade模板中引用它以显示给用户.

对于它的价值,这里是表单的相关部分(使用Jade进行模板化):

form.new-bulletin(name="addbulletin", method="post", enctype="multipart/form-data", action="/addbulletin")
  input(type="file", name="coverimage")
Run Code Online (Sandbox Code Playgroud)

UPDATE

我忘了添加我正在使用connect-multiparty

multipart = require("connect-multiparty"),
multiparty = multipart();
app.post("/addbulletin", multiparty, routes.addbulletin(db));
Run Code Online (Sandbox Code Playgroud)

Nei*_*unn 2

好的,您接下来的教程将使用从上传中获取临时文件信息并将该文件移动到另一个位置的示例。

就目前情况而言,您target_path的代码中包含一个变量,该变量显示在磁盘上的何处查找该文件。因此,如果您想存储引用,那么您就拥有了它,并且将来读取 mongo 文档时将具有该路径信息,以便您可以再次访问该文件。

正如您所说,您可能不想传递整个内容res.body,而只是像这样访问它的属性并构建您自己的文档以在其中插入/更新任何内容。有关访问信息的信息位于File明确文档中。

如果您决定将文件内容放入 mongo 文档中,那么只需读取文件内容即可。这里文件系统操作员的核心节点文档可能会对您有所帮助。特别是读取功能。

从 MongoDB 的角度来看,您可以将该内容添加到任何文档字段,它不会关心并处理二进制类型。前提是您的大小低于 16MB BSON 限制。

超过这个限制并且您可能感兴趣的是GridFS。作为参考,SO 上有一个问题,它可能会为您提供一些关于如何做到这一点的见解。