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?

1
  • 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. Commented Jun 26, 2022 at 9:10

1 Answer 1

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)


  })
})
Sign up to request clarification or add additional context in comments.

Comments

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.