upload images with nodejs

Viewed 300

i have a user.js in model folder

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    profile_pic: {
        data: Buffer,
        contentType: String
    }
    })

i want to upload a profile picture

and in the router folder i defined the storage using multer

const storage = multer.diskStorage({
    destination: (req, file, callback) => {
        callback(null, './images')
    },

    filename: (req, file, callback) => {
        callback(null ,  Date.now()+ file.originalname)
    }

})

const upload = multer({
    storage : storage,
    limits : {
        fieldSize : 1024*1024*3
    }
}) 

router.post('/image' , upload.single('image'),image)

using postman i tried to upload an image .. it uploaded successfully and stored in the defined folder (images)

but i want to store the image in the model too how to store it in the controller folder user.js

1 Answers

Try the example below

const app = require("express")();
const multer  = require('multer')

const firstLocation = multer.diskStorage({
  destination: function (req, file, cb) {');
    cb(null, './imagesFolder/')
  },
  filename: (req, file, callback) => {
    callback(null ,  Date.now()+ file.originalname)
  }
});

const secondLocation = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './modelFolder/')
  },
  filename: (req, file, callback) => {
    callback(null ,  Date.now()+ file.originalname)
  }
});

const firstPath = multer({ storage: firstLocation })
const secondPath = multer({ storage: secondLocation })

function fileUpload(req, res, next) {
  firstPath.single('file')(req, res, next);
  secondPath.single('file')(req, res, next);
  next();
}

app.post("/", fileUpload, (req, res) => {
  res.send("Received file");
});


app.listen(3000, () => {
  console.log("Server started");
});

If you run the above code and send a request to localhost:3000 then you will notice that two directories created named imagesFolder and modelFolder. Inside those folders, you will see the file that you have uploaded.

Updated answer in response to comments for Mongo schema,

const imagePath = '/path/to/myImage.jpg';

const imageUp = mongoose.model('imageUp', UserSchema);

mongoose.connection.on('open', function () {

  imageUp.remove((err) => {
    if (err) throw err;
   
    const up = new imageUp;

    up.img.data = fs.readFileSync(imagePath);  // read from you folder
    up.img.contentType = 'image/jpg';  // set the content tpe to image format

    up.save((err, a) => {      // save or upload image
      if (err) throw err;     // throws error if anything goes wrong

      app.get('/', (req, res, next) => {

        imageUp.findById(up, (err, doc) => { // fetch image from db by id and send in response as required.
          if (err) return next(err);
          res.contentType(doc.img.contentType);
          res.send(doc.img.data);
        });
      });
 }

Ref:- https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/

Related