如何将文件保存到 MongoDB? [英] How do I save a file to MongoDB?

查看:28
本文介绍了如何将文件保存到 MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to save a user selected file to MongoDB. How do I correctly add the file to the BSON object in order to add it to MongoDB? If my approach is incorrect please point in the right direction.

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

Below is the client code. This jQuery functions gathers the text (need help on the file part) on every input field and sends it to the server as a BSON object.

$('#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);
            });

表单的 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>

CoffeeScript 中的服务器端代码:

The server side code in 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

推荐答案

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

To store files in MongoDB you should try to use GridFS.
You can find some tutorials about working with GridFS (example).
Check your MongoDB Driver's API and try to implement it in your project

这篇关于如何将文件保存到 MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆