将 data:image 插入 MongoDB

Inserting a data:image into MongoDB

我正在尝试将图像插入到 MongoDB collection 中,如下所示-

客户

var myInfoId = "";
myInfo.findOne({"userID": Meteor.userId()});
myInfoId = myInfoId._id;

var file = theTemplate.find('#myGraphic').files[0];
if (file)
{
    var reader = new FileReader();
    reader.onload = function(e) {
        Meteor.call('updateMyInfo', myInfoId, e.target.result);
        console.log("file = " + e.target.result);
     }
    reader.readAsDataURL(file);
} 

服务器

Meteor.methods({
    'updateMyInfo': function(myInfoId, myGraphic){
        console.log("file = " + myGraphic);
        myInfo.update (
            {"_id": myInfoId},
            {$set: {"myGraphic": myGraphic}}    
        )
    }
})

在这两个日志中,我可以看到类似 -

的数据
 file = data:image/jpeg;base64,/9j/4AAQSkZ.....

但该数据从未进入 Collection。我将最大图像大小设置为 200x200px,因此数据量永远不会超过 24k,所以我认为没有必要将数据分块。我需要做什么才能插入该信息?

问题出在您设置 id

的最开始
var myInfoId = "";
myInfo.findOne({"userID": Meteor.userId()});
myInfoId = myInfoId._id;

第一行初始化一个变量,第二行进行 mongo 查找但不对结果做任何事情,第三行只是将初始变量设置为未定义的 属性。

var myInfoId = myInfo.findOne({userID: Meteor.userId()})._id;

这应该有效。

此外,由于您在客户端和服务器上处于同一用户会话(连接)中,因此您无需从客户端进行设置。事实上,您可以将整个代码更改为:

客户

var file = theTemplate.find('#myGraphic').files[0];
if (file)
{
    var reader = new FileReader();
    reader.onload = function(e) {
        Meteor.call('updateMyInfo', e.target.result);
     }
    reader.readAsDataURL(file);
} 

服务器

Meteor.methods({
    'updateMyInfo': function(myGraphic){
        myInfo.update (
            {myInfo.findOne({userID: Meteor.userId()})._id},
            {$set: {myGraphic: myGraphic}}    
        )
    }
})