1

I am using NodeJS + Express. I submit a form, with a file to create an account. If I want to update that account, and don't want to update the image. Here is my code:

uploadAndSave: function (image, cb) {
    if (!image) return this.save(cb)
    var self = this
    uploader.upload({'large': 300, 'small':150}, image,function(fileName){
    self.logo.filename = fileName;
    self.logo.cdnUri = 'https://myapp.s3.amazonaws.com/';
    self.save(cb);
});

And in my controller:

exports.update = function(req, res){
    var account = req.account
    account = _.extend(account, req.body)
    account.uploadAndSave(req.files.image, function(err) {
    if (err) {
      res.render('accounts/edit', {
        title: 'Edit Account',
        account: account,
        errors: err.errors
      })
    }
    else {
      res.redirect('/accounts/' + account._id)
    }
  })
}

req.files.image is always have some value. I guess, after first file upload, this variable is set, and never removed. How can I remove it?

Burak
  • 5,706
  • 20
  • 70
  • 110

1 Answers1

0

This property is an object of the files uploaded. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used.

source: http://expressjs.com/api.html#req.files

Since it's always an object !image will always return true. To check if an object is empty or not you can use the following techniques.

I prefer Object.keys(obj).length === 0 although this only works in 'modern' browsers.

Community
  • 1
  • 1
Pickels
  • 33,902
  • 26
  • 118
  • 178