Search code examples
node.jsmongodbexpressmulter

File Upload Express MongoDB Multer


I'm trying to upload a image to my Express Rest Api. I'm using Multer to parse the multipart/form image. I would like to know whats best practice in saving images on the server or in the database. And how I can make this happen with Multer.

the user model:

var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
    email: {
        type: String,
        required: true
    },
    avatar: {
        data: Buffer,
        contentType: String
    }
});
var User = module.exports = mongoose.model('user', userSchema, 'user');
module.exports.addUser = function(user, callback) {
    User.create(user, callback);
};

the user router:

import multer from 'multer';
var upload = multer({ dest: 'uploads/' })

import User from '../models/user.js';
router.post('/register', upload.single('avatar'), (req, res) => {           
    var user = req.body;
    user.avatar = req.file;   //img file in the req.file
    User.addUser(user, (err, user) => {
        if(err) throw err;
        res.json({
            success: true,
            user: user
        });
    })
});

This doesn't throw me any errors, but the image is not being uploaded to the db. Any Help would be appreciated. (the file is in the upload dir on the server with a 7-bit encoding)


Solution

  • If you want to store images directly into database you have to use fs.readFileSync to get the image as binary and then save it, note that req.file.path returns the full path of the uploaded file:

    var user = req.body;
    user.avatar.data = fs.readFileSync(req.file.path);
    user.avatar.contentType = req.file.mimetype;
    
    User.addUser(user, (err, user) => {
        ...
    });
    

    Keep in mind that storing images as strings that represent their urls could be better and easier than using the first approach, read this post for more information