如何将文件保存到MongoDB?

22 file-upload mongodb

我想将用户选择的文件保存到MongoDB.如何将文件正确添加到BSON对象以将其添加到MongoDB?如果我的方法不正确,请指出正确的方向.

以下是客户端代码.这个jQuery函数在每个输入字段上收集文本(需要文件部分的帮助),并将其作为BSON对象发送到服务器.

$('#add').click(function()
            {
                console.log('Creating JSON object...');
                var classCode = $('#classCode').val();
                var professor = $('#professor').val();
                var description = $('#description').val();
                var file = $('#file').val();

                var document = 
                {
                    'classCode':classCode,
                    'professor':professor,
                    'description':description,
                    'file':file,
                    'dateUploaded':new Date(),
                    'rating':0 
                };
                console.log('Adding document.');
                socket.emit('addDocument', document);
            });
Run Code Online (Sandbox Code Playgroud)

表格的HTML:

   <form>
        <input type = 'text' placeholder = 'Class code' id = 'classCode'/>
        <input type = 'text' placeholder = 'Document description' id = 'description'/>
        <input type = 'text' placeholder = 'Professor' id = 'professor'/>
        <input type = 'file' id = 'file'/>
        <input type = 'submit' id = 'add'/>
    </form>
Run Code Online (Sandbox Code Playgroud)

CoffeeScript中的服务器端代码:

#Uploads a document to the server. documentData is sent via javascript from submit.html
            socket.on 'addDocument', (documentData) ->
                console.log 'Adding document: ' + documentData
                db.collection 'documents', (err, collection) ->
                    collection.insert documentData, safe:false
                    return
Run Code Online (Sandbox Code Playgroud)

pau*_*kow 36

如果您的文件足够小(小于16兆字节),您可以将文件嵌入到BSON文档中,而不是添加GridFS的复杂性.

BSON具有二进制数据类型,任何驱动程序都应该为其提供访问权限.

如果您的文件是文本文件,则可以将其存储为UTF8字符串.

  • 你能举例说明如何使用这种类型吗?我的文件系统上有文件 - 如何将其放入数据库? (4认同)

Ser*_*ruk 16

要在MongoDB中存储文件,您应该尝试使用GridFS
您可以找到一些有关使用GridFS的教程(示例).
检查MongoDB驱动程序的API并尝试在项目中实现它

  • 我一直在阅读有关GridFS的内容,但我找不到一个示例,说明如何将文件从客户端发送到服务器以便将其保存在GridFS中.有任何来源? (2认同)