2

I'm trying to upload an image to the file system with Multer. Please take a look at the relevant data in my route:

const
  ..
  multer = require('multer'),
  ..;

const storage = multer.diskStorage({
    destination: function (req, file, callback) {
      callback(null, './uploads');
    },
    filename: function (req, file, callback) {
      callback(null, req.params.id + file.originalname);
    }
  }),
  upload = multer({storage: storage}).single('profilePic');

router.put(
  '/:id',
  middleware.isLoggedIn,
  (req, res, next) => {

    User
      .findByIdAndUpdate(
        req.params.id, req.body.user,
        (err, updatedUser) => {
          if (err) {
            return req.flash('error', err.message);
          }

          upload(req, res, (err) => {
            if (err) {
              eval(locus);
              return req.flash('error', err.message);
            }
            updatedUser = req.body.user;
            eval(locus);

            //redirect show page
            res.redirect('/dashboard/profile/' + req.params.id + '/edit');
          });
        });
  });

module.exports = router;

When I look at updatedUser the first thing I see is { profilePic: 'data:image/jpeg;base64,....} what am I doing wrong? It's not even updating the page now that I have the upload function in here. What I really want to do is get the destination to work on s3 but I need to get this to save first.

Joseph Chambers
  • 3,698
  • 4
  • 22
  • 37

1 Answers1

2

So, this is a the most basic example of uploading an image using multer:

var express = require('express')
var multer = require('multer')
var app = express()

var storage = multer.diskStorage({
  // define where the file should be uploaded, else it will be uploaded to the system temp dir
  destination: function (req, file, cb) {
    // ./uploads should be created beforehand
    cb(null, './uploads')
  },
  // define "filename", else a random name will be used for the uploaded file
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + file.originalname)
  }
})

var upload = multer({ storage: storage })

// pic is the name of image field in the form
app.put('/profile', upload.single('pic'), function (req, res, next) {
  console.log(req.file)
  res.send('Uploaded')
})

app.listen(3000)

And here is an example curl command to upload an image from the file system to the above app:

curl -X PUT -F 'pic=@/projects/eg/foto.png' localhost:3000/profile

Make sure the example works fine, to ensure you understand how multer handles file uploads, and that the issue is not with multer.

That said and done, User.findByIdAndUpdate seems to be storing the image data as a base64 encoded string somewhere; I have no idea what User.findByIdAndUpdate connects to. It is beyond the domain of multer.

Someone on our Gitter channel (https://gitter.im/expressjs/express) might be able to suggest something. Join us there.

Hage Yaapa
  • 521
  • 3
  • 4