Home > Enterprise >  How to decode binary image data retrieved from mongodb in nodejs
How to decode binary image data retrieved from mongodb in nodejs

Time:03-10

I am trying to upload and retrieve image to and from mongodb through nodejs and mutter. But i am stuck some where, i hope i am succeeded in uploading image as binary data. but not displaying image in my .ejs file.

Routes file

    const express=require('express');
    const adminRouter=express.Router();
    const Bookdata=require('../model/Bookdata')
    const multer = require('multer');
    const path = require('path');
    var fs = require('fs');
    const {
      GridFsStorage
    } = require("multer-gridfs-storage");
     
    require("dotenv")
      .config();
    
    
    // set up multer for storing uploaded files
    const storage=multer.diskStorage({
      //destination for files
      destination:function(request,file,callback){
        callback(null,'../LibraryApps/public/uploads/images');
      },
      //add back the extensions
      filename:function(request,file, callback){
      
        callback(null,file.fieldname Date.now() path.extname(file.originalname));
      }
    })
    
    //upload parameters for mutter
    const upload = multer({ 
      storage: storage,
      limits:{
        fileSize: 1000000
      },
      fileFilter:function(req,file,callback){
        checkFileType(file, callback);
      }
    });
    //Check file type
    function checkFileType(file, callback){
    
      // allowed extension
      const filetypes = /jpeg|jpg|png|gif/;
      //check extension
      const extname=filetypes.test(path.extname(file.originalname).toLowerCase());
      //check mime
      const mimetype=filetypes.test(file.mimetype);
      if(mimetype&&extname){
        return callback(null, true);
      }else{
        callback('Error: Images only');
      }
    }
    var imgModel = require('../model/Bookdata');
    
    function router(nav){
    adminRouter.get('/',function(req,res){
       
    
        imgModel.find({}, (err, items) => {
          if (err) {
              console.log(err);
              res.status(500).send('An error occurred', err);
          }
          else {
              //res.render('imagesPage', { items: items });
              res.render('addBook',{
                nav,
                title:'Library'
                
            })
          }
      });
    })
    
    adminRouter.post('/add',upload.single(`image`), function(req,res){
      // res.send("Hey I am Added");
      console.log(req.file);
      var item={
        title: req.body.title,
        author: req.body.author,
        genre: req.body.genre,
        //image: req.file.image,
        image: {
          data: fs.readFileSync(path.join('../LibraryApps/public/uploads/images/'   req.file.filename)),
          contentType: 'image/png'
      }
      }
      imgModel.create(item, (err, item) => {
        if (err) {
            console.log(err);
        }
        else {
          var book=Bookdata(item);
          book.save();
          res.redirect('/books');
        }
    });
     
    
    });
    return adminRouter;
    }
    module.exports=router;

my model file

    //Accessing Mongose package
    const mongoose=require('mongoose');
    
    //Database connection
    // mongoose.connect('mongodb://localhost:27017/library');
    mongoose.connect('mongodb....');
    //Schema definition
    const Schema= mongoose.Schema;
    
    const BookSchema=new Schema({
        title: String,
        author: String,
        genre: String,
       // image: String,
        image:{
            data: Buffer,
            contentType: String
        }
    });
    
    //Model creation
    var Bookdata= mongoose.model('bookdata',BookSchema);
    module.exports=Bookdata;

and this is my .ejs file

<%for(i=0;i<books.length;i ){%>

  <div >    
        <br>
        <div >
          <a  href="#">
           
            <img src="data:<%=books[i].image.contentType%>;base64,{Buffer.from('<%=books[i].image.data%>','binary').toString('base64')}"  style="width:100px;height:100px" >
          </a>
       
        </div>

my get function

 booksRouter.get('/',function(req,res){
            Bookdata.find()
            .then(function(books){
              res.render("books",{
                nav,
                title:"Library App",
                books
              });
            })
            
           
          });
      

in mongodb, i am getting like this

> _id:6226e5c60e92bdee82dc574a title:"cc" author:"aa" genre:"life" image:Object
> data:Binary('iVBORw0KGgoAAAANSUhEUgAAA gAAAOECAYAAAAylRvFAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYA...',
> 0) contentType:"image/png"
> __v:0

In Console i am getting error

GET data:image/png;base64,{Buffer.from('�PNG

���
IHDR���������2�����gAMA�����a���sRGB������� cHRM��z&��������������u0���`��:���p��Q<���bKGD�������������	pHYs������� ����IDATx���W�$ו�	�k�pZ��H(�*g���NWw��y�b.�b~��I�b.�3]�d�$HB%�D���ҵ�������EDF&�VH���ws�����k�o��*����x<����x�W�?����x<����|�x���x<����x<�������x<����x���x<����x<�������x<����x���x<����x<�������x<����x���x<����x<�������x<�������0�������0�Y\5_D���x<����x<���ѱ���Pб�-S�-����E�g��Ya>^��ź���x<����|[������W�t=��L��̮jf��B�s����x<�������,�*(�Kx&�.Lb�
� ސ|A���"/eÏ�������x<���]� net::ERR_INVALID_URL

enter image description here

my mongodb

enter image description here

CodePudding user response:

in the template, just add the properties:

edit: Buffer.from is not needed, as it's already a buffer:

with for loop:

<%for(i=0;i<books.length;i  ){%>

  <div >
        <br>
        <div >
          <a  href="#">

            <img src="data:<%=books[i].image.contentType%>;base64,<%=books[i].image.data.toString('base64')%>"  style="width:100px;height:100px" >
          </a>

        </div>
 <% } %>
  • Related