使用Express保存file upload到MongoDB

在本教程之后 ,我设法创build了一个带有fileinput的表单,将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 (非文件input的其他表单字段)插入Mongo数据库。 我想只需要在req.files上插入req.body ,但这不起作用。

我想,我的混淆之处在于蒙戈如何运作。 我不是数据库专家,但是当你“上传”一个图像时,实际的图像文件应该到数据库,还是应该只添加一个引用(如图像名称和应用程序的位置)?

所以总的来说,我只是想将上传的图像(或其引用)保存到Mongo数据库,然后我可以在Jade模板中引用它以向用户显示。

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

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

UPDATE

我忘了补充说我正在使用connect-multiparty

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

好的,所以你正在使用的教程是从上传文件中获取临时文件信息,然后将该文件移动到另一个位置。

因此,您的代码中有target_pathvariables,它显示了在磁盘上查找文件的位置。 所以如果你想存储一个引用 ,那么你已经有了它,将来你的mongo文件将会有这个path信息,所以你可以再次访问这个文件。

正如你所说的,你可能不想传入整个res.body ,只是像这样访问它的属性,并构build你自己的文档,插入/更新任何内容。 有关访问File信息的信息在快速文档中 。

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

从MongoDB的angular度来看,您可以将该内容添加到任何文档字段,它不会在意和处理二进制types。 只要你的尺寸低于16MB的BSON限制。

超过这个限制,也许你感兴趣的是GridFS 。 有关这个问题 ,可以提供一些关于如何做到这一点的见解。