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

时间:2014-02-22 04:03:36

标签: node.js mongodb file-upload express

this tutorial之后,我设法创建了一个带有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("/");
            }
        });

    }
};

第二部分是将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")

更新

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

multipart = require("connect-multiparty"),
multiparty = multipart();
app.post("/addbulletin", multiparty, routes.addbulletin(db));

1 个答案:

答案 0 :(得分:2)

好的,所以您关注的教程是使用从上传中获取临时文件信息的示例,并移动该文件到另一个位置。

现在,您的代码中有target_path变量,该变量显示了在磁盘上找到文件的位置。因此,如果您想要存储引用,那么您可以使用它,并且将来对您的mongo文档的读取将具有该路径信息,以便您可以再次访问该文件。

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

如果您决定将文件内容放入mongo文档中,那么只需读取文件内容即可。这里是File System运算符的核心节点文档可能对你有所帮助。特别是read函数。

从MongoDB的角度来看,您只需将该内容添加到任何文档字段,它就不会关心和处理二进制类型。如果您的尺寸低于16MB BSON限制。

超过这个限制,也许你感兴趣的是GridFS。作为参考,SO上有this question可以为您提供有关如何执行此操作的一些见解。