0

I am trying to store images in mongodb as binary and later display that on the screen

I think I need to use multer for this.

This is code I used to store the image.

// code in router.post("/uploads" ...
const item = new Item(
    {
        name : name,
        desc : desc,
        image :
        {
            data : fs.readFileSync(file.path),
            contentType : file.mimetype
        }
    }
);

And this is code I used to retrieve the image

// code in router.get("display" ...
// I was able to retrieve information correctly from mongodb
res.render('display',
       {name : item.name,
        desc : item.desc,
        image : 
        {
            data : item.image.data,
            contentType : item.image.contentType
        }});

// and in ejs file I have
<p class="lead d-none d-sm-block"><%= item.name %></p>
<img src="/<%= item.image.data %>" contentType="<%= item.image.contentType %>"> 

But it's not showing image correctly.

Could you tell me what I missed here?

BK C.
  • 573
  • 2
  • 7
  • 16
  • Did the answer bellow answered your question ? If yes mark it as accepted. Since it has been 2 years, you may also have resolved this issue, you can share it as an answer. – Ambroise Rabier Jun 26 '22 at 09:10

1 Answers1

1

in HTML side

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MY APP</title>
</head>
<body>


 <!--  SINGLE FILE -->
<form action="/uploadfile" enctype="multipart/form-data" method="POST"> 
   <input type="file" name="myFile" />
   <input type="submit" value="Upload a file"/>
</form>


<!-- MULTIPLE FILES -->

<form action="/uploadmultiple"  enctype="multipart/form-data" method="POST">
  Select images: <input type="file" name="myFiles" multiple>
  <input type="submit" value="Upload your files"/>
</form>

  <!--   PHOTO-->

<form action="/upload/photo" enctype="multipart/form-data" method="POST"> 
  <input type="file" name="myImage" accept="image/*" />
  <input type="submit" value="Upload Photo"/>
</form>
</body>
</html>

in server side and POST function should be like this code:

Uploading a Single File

app.post('/uploadphoto', upload.single('picture'), (req, res) => {
    var img = fs.readFileSync(req.file.path);
 var encode_image = img.toString('base64');
 // Define a JSONobject for the image attributes for saving to database

 var finalImg = {
      contentType: req.file.mimetype,
      image:  new Buffer(encode_image, 'base64')
   };
db.collection('quotes').insertOne(finalImg, (err, result) => {
    console.log(result)

    if (err) return console.log(err)

    console.log('saved to database')
    res.redirect('/')


  })
})

Uploading Multiple Files

app.post('/uploadmultiple', upload.array('myFiles', 12), (req, res, next) => {
  const files = req.files
  if (!files) {
    const error = new Error('Please choose files')
    error.httpStatusCode = 400
    return next(error)
  }

    res.send(files)

})

Retrieving Stored Images

To retrieve the stored images, we perform a MongoDB search using the find method and return an array of results. We then go on and obtain the _id attributes of all the images and return them to the user.

app.get('/photos', (req, res) => {
db.collection('mycollection').find().toArray((err, result) => {

      const imgArray= result.map(element => element._id);
            console.log(imgArray);

   if (err) return console.log(err)
   res.send(imgArray)

  })
});

Since we already know the id's of the images, we can view an image by passing its id in the browser, as illustrated below.

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

db.collection('mycollection').findOne({'_id': ObjectId(filename) }, (err, result) => {

    if (err) return console.log(err)

   res.contentType('image/jpeg');
   res.send(result.image.buffer)


  })
})
mohammad javad ahmadi
  • 2,031
  • 1
  • 10
  • 27