mmm
mmm

Reputation: 2297

Multer not uploading files when I include logic in onFileUploadStart() - NodeJs

I'm trying to use multer to upload only image files with node

File's upload successfully with this:

app.use(multer({
  dest: __dirname + '/public/uploads/',
  onFileUploadData: function (file, data) {
    console.log(data.length + ' of ' + file.fieldname + ' arrived');
  },
  onFileUploadComplete: function (file) {
    console.log(file.fieldname + ' uploaded to  ' + file.path);
  }
}));

But I want to limit it to images only and add some user authentication (user auth not implemented yet in the example below).

When I start the server with onFileUploadStart included, it'll log to the console that it uploaded, but when I check my uploads folder, nothing is there.

app.use(multer({
  dest: __dirname + '/public/uploads/',
  onFileUploadStart: function (file) {
    console.log(file.mimetype);
    if (file.mimetype !== 'image/png' || file.mimetype !== 'image/jpg' || file.mimetype !== 'image/jpeg') {
      return false;
    } else {
      console.log(file.fieldname + ' is starting ...');
    }
  },
  onFileUploadData: function (file, data) {
    console.log(data.length + ' of ' + file.fieldname + ' arrived');
  },
  onFileUploadComplete: function (file) {
    console.log(file.fieldname + ' uploaded to  ' + file.path);
  }
}));

Upvotes: 2

Views: 3061

Answers (1)

mscdex
mscdex

Reputation: 106698

The problem is with your boolean logic.

This:

if (file.mimetype !== 'image/png' || file.mimetype !== 'image/jpg' || file.mimetype !== 'image/jpeg')

should instead be:

if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg')

Upvotes: 2

Related Questions