0

How do I create a web gallery and uploading, storing and displaying images via nodejs and mongodb?

I have tried to write some code myself, but don't manage to solve the problem.

Do someone have a link or tutorial that helps me solve the problem?

Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
beastlike
  • 1
  • 2
  • I don't work with Node.js but storing data in MongoDB is possible by either storing a `Base64` encoding of your file in a field (file size <= 16MB) or GridFS (file size > 16MB). Since images are most likely smaller than 16MB, you simply need your Node.js application to read the file and write the byte[] into a base64 encoded string object (from Java POV). See https://stackoverflow.com/questions/28834835/readfile-in-base64-nodejs – jAC May 22 '17 at 13:13

1 Answers1

0

It is not recommended to store whole images on databases. It can be done but based on similar questions on stack overflow it is better to store images on your file system. That can be done by using themulterand fs module to handle the upload and store it on the file system. You can even use an image proccessor to confirm that what was uploaded was really an image and not something else. I recommend using the sharp module found on npm to do that. This way you are sure that nothing can go wrong and you can even resize images before storing. Here is some code for this using express.js:

    var multer = require('multer');
    var uploadPicture = multer({
    dest: 'temp/'
    });
    var sharp = require('sharp');

    app.post('/upload', uploadPicture.single('profileIcon'), function (req,res) {
      fs.readFile(req.file.path, function (err, data) {
        if (err) res.end('UNRESOLVABLE ERROR');
    sharp(data).resize(200, 200).toFile('./photos/pic.jpg', function (err, info) {
    //DELETE THE TEMPORAL FILE
            fs.unlink(req.file.path, function (error) {
                if (error) res.end('UNRESOLVABLE ERROR'); //CODE 3 ALARM
                res.end('success');
            });
    }
itsundefined
  • 1,409
  • 2
  • 12
  • 32
  • 1
    `It is not recommended to store whole images on databases`. I disagree. This is mostly a problem with conventional, relational database management systems. Storing binary files in MongoDB shouldn't be a problem at all. It even specifically gives you the opportunity to do so via GridFS (for larger files) – jAC May 22 '17 at 13:26
  • That makes sense. I always used relational databases and that's why I read that. – itsundefined May 22 '17 at 13:28