1

I managed to save image to mongoDB with type Buffer. Together with the image is the username of the user currently logged in. MY problem now is to display the image(s) to the client's side. Much appreciated if it has a condition like "display image where username = 'currentUser_username'". I also have an 'uploads' folder where the images are saved. Please help. I'm a newbie in nodeJS. Please be very detailed in ur answer. Thanks

2
  • post some code or the logic you have tried so far... Commented Apr 10, 2017 at 4:49
  • Just place the url on the `<img src={"data-url-here"} />, and you're good to go. Commented Apr 10, 2017 at 5:24

1 Answer 1

3

To send the image to the client, you need to save image binary data, image content type.

The structure of your schema should be like this.

var demoSchema = new mongoose.Schema({
    imageData : { type: Buffer },
    imageType : {type: String },
    imageName : {type: String }
})

mongoose.model('Demo', demoSchema)

On saving your image to DB, save the content type too (must).

var data = fs.readFileSync(incomingImage.path);
var input = new Demo():
input.image = new MongoDb.Binary(data);
input.imageType = incomingImage.type;
input.imageName = incomingImage.name;

input.save();

When you retrieve from DB and send the contentType and mention the buffer as binary to the client.

Demo.findById(req.params.id, function (error, result) {
    res.contentType(result.imageType);    
    res.end(result.image.buffer, "binary");
});

If you need some brief detail see here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the answers. These are all helpful. I'll try all of these :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.