Read/write binary data to MongoDB in Node.js

时光怂恿深爱的人放手 提交于 2021-02-07 09:15:48

问题


I've been able to successfully write binary data (an image) to MongoDB in Node.js. However I can't find clear documentation on how to read it back.

Here's how I'm writing the image to MongoDB:

var imageFile = req.files.myFile;
var imageData = fs.readFileSync(imageFile.path);

var imageBson = {};
imageBson.image = new db.bson_serializer.Binary(imageData);
imageBson.imageType = imageFile.type;

db.collection('images').insert(imageBson, {safe: true},function(err, data) {

I'd appreciate any pointers on reading the image from Mongo using Node. I'm assuming there's a function like "db.bson_deserializer...". Thanks!


回答1:


Found the answer:

        var imageFile = req.files.myFile;
    fs.exists(imageFile.path, function(exists)  {

        if(exists)
        {
            console.log("File uploaded: " + util.inspect(imageFile));
            fs.readFile(imageFile.path, function(err, imageData) {
                if (err) {
                    res.end("Error reading your file on the server!");
                }else{
                    //when saving an object with an image's byte array
                    var imageBson = {};
                    //var imageData = fs.readFileSync(imageFile.path);
                    imageBson.image = new req.mongo.Binary(imageData);
                    imageBson.imageType = imageFile.mimetype;
console.log("imageBson: " + util.inspect(imageBson));

                    req.imagesCollection.insert(imageBson, {safe: true},function(err, bsonData) {

                        if (err) {
                            res.end({ msg:'Error saving your file to the database!' });
                        }else{
                            fs.unlink(imageFile.path); // Deletes the file from the local disk
                            var imageBson = bsonData[0];
                            var imageId = imageBson._id;
                            res.redirect('images/' + imageId);
                        }
                    });
                }
            });
        } else {
            res.end("Oddly your file was uploaded but doesn't seem to exist!\n" + util.inspect(imageFile));
        }
    });


来源:https://stackoverflow.com/questions/24647197/read-write-binary-data-to-mongodb-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!