sudipt dabral
sudipt dabral

Reputation: 1485

having problem with storing and getting image in mongoDb with multer?

This is my router file!

router.post('/add', upload.single('image'), (req, res) => {
    console.log(req.file)
    var img = fs.readFileSync(req.file.path);
    var encode_image = img.toString('base64');

    const image = new Image({
        image: Buffer.from(encode_image, 'base64'),
        contentType: req.file.mimetype
    })

    image.save()
         .then(img => {
             res.json(img.id)
         })
         .catch(err => res.json(err))

})
// 5e252bd7e4eaa9478c019f02

My schema for image upload

// Create Image Schema
const ImageSchema = new Schema({
    image: {
        type: Buffer
    },
    contentType: {
        type: String
    },
    uploaded: {
        type: Date,my 
        default: Date.now
    }
})

But after being uploading image to db my database

Image of record in collection

but when I try to retrieve it as:

router.get('/photo/:id', (req, res) => {
    var filename = req.params.id;

    Image.findOne({'_id': mongoose.Types.ObjectId(filename) }, (err, result) => {

        if (err) return console.log(err)
        console.log(result)

       res.contentType(result.contentType);
       res.send(result.image.buffer)


      })
    })

I get a black screen without the image, I referred this for making the file upload.

Upvotes: 1

Views: 724

Answers (2)

sudipt dabral
sudipt dabral

Reputation: 1485

Okay so I resolved the error by doing so :-= changing

 res.send(result.image.buffer)

To

 res.send(new Buffer.from(result.image.buffer, 'base64'))

I dont know why this worked ! If anyone know kindly let me know . Thank you

Upvotes: 1

Prakash Karena
Prakash Karena

Reputation: 2595

It look's like problem with storing image to database

 const image = new Image({
        image: new Buffer.from(encode_image, 'base64'), // pass new object of Buffer with your image 
        contentType: req.file.mimetype
    })

Upvotes: 0

Related Questions