How to Save and Recover Images in Base64 using Mongoose in a Nodejs Service?

Asked

Viewed 828 times

1

I need to save and recover an image in Base64 through a REST service developed with Nodejs. For this, I have created the following schema on Mongo:

const userSettingsSchema = new Schema(
    {
        'avatar': { type: Buffer, contentType: String, required: false}
    }
);

To persist the image, I sent the code Base64 of the image (https://www.base64-image.de/) in a post request for the service passing in the body of the request the JSON:

{
    "avatar": "data:image/jpeg;base64,/9j[...]"
}

When I see it in the bank, the avatar is shown in a binary Buffer format:

inserir a descrição da imagem aqui

The problem is that when I try to recover the image by the GET api, it returns with this binary value, and not as Base64:

inserir a descrição da imagem aqui

What I need to do to get the image in Base64?

1 answer

2


You can transform Arraybuffer to Base64 as follows

var base64Image = new Buffer(arrayBuffer, 'binary').toString('base64');

Where the arraybuffer in your case would be documento.avatar.data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.