Millenial2020
Millenial2020

Reputation: 2913

How to save base64 directly to mongoose in express js

I want to save an image not in my server but in my database.

this is my model

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var categorySchema = new Schema({
    img: { data: Buffer, contentType: String },
});

module.exports = mongoose.model('Category', categorySchema);

now in my router I'm getting this base64 image with a long string.

{ '$ngfDataUrl': 'data:image/png;base64,long-String'}

I want to know how do I save this information in my mongoose db database so far i have this.

router.post('/add', function (req, res) {

var category = new Category();
category.img.data = req.body.category.img;

category.img.contentType = 'image/png';

category.save(function (err) {
    if (err) throw new Error(err);
    res.sendStatus(200)
});

but obviously that is not working i get this error.

Error: ValidationError: CastError: Cast to Buffer failed for value "{ '$ngfDataUrl': 'data:image/png;base64, long-String'}

Thanks in advance I'm in saving files.

Upvotes: 3

Views: 11798

Answers (1)

dvlsg
dvlsg

Reputation: 5538

You'll want to actually pull out the base64 string from the request body, and save that.

Is req.body.category.img equal to { '$ngfDataUrl': 'data:image/png;base64,long-String' }, where long-String is the base64 representation of the image?

If so, do something like this:

const category = new Category();

const img = req.body.category.img;

const data = img['$ngfDataUrl'];
const split = data.split(','); // or whatever is appropriate here. this will work for the example given
const base64string = split[1];
const buffer = Buffer.from(base64string, 'base64');

category.img.data = buffer;

// carry on as you have it

Upvotes: 3

Related Questions