我想将用户选择的文件保存到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字符串.
| 归档时间: |
|
| 查看次数: |
65785 次 |
| 最近记录: |