Search code examples
node.jsmongodbmulter

Retrieving images stored in mongodb


I have tried to retrieve images I uploaded and saved to mongodb but I am not able to retrieve back the image directly from db. There seems to be a lot of information about uploading files but not a lot of information about retrieving the uploaded images from the db.

I would really appreciate your help. Thanks in advance.

This is part of what is saved in mongodb:

{
    "_id": {
        "$oid": "58f2e56fd8ca891e02fc85db"
    },
    "path": "uploads/1492313455338_codi.jpg",
    "filename": "1492313455338_codi.jpg",
    "__v": 0,
    "article": {
        "$oid": "58f2e56fd8ca891e02fc85dc"
    }
}

Schema:

var mongoose = require('mongoose');

var ImageSchema = new mongoose.Schema({
  img: { data: Buffer, contentType: String }
});

module.exports = mongoose.model('Image', ImageSchema);

router.js

router.post('/blog/article/addPost', upload.single('image'), function(req, res, err) {
  var image = new Image ({
    path: req.file.path,
    filename: req.file.filename
  });
    image.save(function(err, image) {
          //other code
        });
});

Part of ejs to upload file

<form action="/blog/article/addPost" method="post" enctype="multipart/form-data">
        <div class="form-group">
          <label="name">Add a picture for your article</label>
          <input id="upload-input" type="file" class="form-control" name="image"/>
        </div>
</form>

ejs to retrieve file:

<div class="col-md-4">
        <form method="GET" action="/blog/article/<%= image.id %>">
          <img src="<%= image.path %>" style="width:304px;height:228px;">
        </form>
</div>

multer configuration:

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads/')
  },
  filename: function (req, file, cb) {
    if (!file.originalname.match(/\.(png|jpeg|jpg|wav|tif|gif)$/)) {
      var err = new Error();
      err.code = 'filetype';
      return cb(err);
    } else {
      cb(null, Date.now() + "_" + file.originalname);
    }

  }
});

Solution

  • I had to remove 'public' from the path. This link helped me resolve the issue