1

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 class="row">    
        <br>
        <div class="col-md-2 col-sm-3 text-center">
          <a class="story-title" href="#">
           
            <img src="data:<%=books[i].image.contentType%>;base64,{Buffer.from('<%=books[i].image.data%>','binary').toString('base64')}"  style="width:100px;height:100px" class="img-circle">
          </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('%EF%BF%BDPNG%0A%1A%0A%EF%BF%BD%EF%BF%BD%EF%BF%BD%0AIHDR%EF%BF%BD%EF%BF%BD%03%EF%BF%BD%EF%BF%BD%EF%BF%BD%03%EF%BF%BD%08%06%EF%BF%BD%EF%BF%BD%EF%BF%BD2%EF%BF%BD%1B%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%04gAMA%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%0B%EF%BF%BDa%05%EF%BF%BD%EF%BF%BD%EF%BF%BD%01sRGB%EF%BF%BD%EF%BF%BD%EF%BF%BD%1C%EF%BF%BD%EF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F%BD%7F%02%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%0B%EF%BF%BD0%EF%BF%BDY\5%7F_D%EF%BF%BD%EF%BF%BD%EF%BF%BDx%3C%1E%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BDx%3C%EF%BF%BD%EF%BF%BD%EF%BF%BD%D1%B1%12%EF%BF%BD%EF%BF%BD%EF%BF%BDP%D0%B1%10%EF%BF%BD%19%11-S%EF%BF%BD-%EF%BF%BD%12%EF%BF%BD%EF%BF%BD%EF%BF%BD%13E%EF%BF%BDg%EF%BF%BD%EF%BF%BDYa%3E^%EF%BF%BD%EF%BF%BD%C5%BA%EF%BF%BD%EF%BF%BD%EF%BF%BDx%3C%1E%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD|[%EF%BF%BD%08%EF%BF%BD%0F%EF%BF%BD%EF%BF%BD%08%EF%BF%BD%EF%BF%BD%08W%EF%BF%BD%0Bt=%EF%BF%BD%EF%BF%BDL%EF%BF%BD%EF%BF%BD%CC%AEjf%EF%BF%BD%EF%BF%BDB%EF%BF%BD%0Bs%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BDx%3C%1E%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%11%EF%BF%BD%1F,%EF%BF%BD*(%02%EF%BF%BDKx&%EF%BF%BD.Lb%EF%BF%BD%0A%EF%BF%BD+%DE%90|A%EF%BF%BD%EF%BF%BD%EF%BF%BD%22/e%C3%8F%EF%BF%BD%EF%BF%BD%17%EF%BF%BD%1E%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BDx%3C%1E%EF%BF%BD%EF%BF%BD%EF%BF%BD]%EF%BF%BD net::ERR_INVALID_URL

enter image description here

my mongodb

enter image description here

1 Answer 1

1

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 class="row">
        <br>
        <div class="col-md-2 col-sm-3 text-center">
          <a class="story-title" href="#">

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

        </div>
 <% } %>
Sign up to request clarification or add additional context in comments.

11 Comments

if i changed like this i am getting error: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
@Elizabeth the ejs syntax is messed up, you have extra scriptlet tags and quotes, check the updated code
i am getting error: Failed to load resource: net::ERR_INVALID_URL
@Elizabeth make sure you clean up all the previous data, and try uploading a new image
@Elizabeth great. so, Buffer.from is not needed, as it's already a buffer..
|

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.