Search code examples
node.jsmongodbexpressmulter

Node - multer - Problems with file uploading


I'm trying to do file uploading using multer. The upload done right, but the problem is that I wanna just upload .avi files and any file is being accepted and uploaded. I've already set up the multer configs with fileFilter, but seems it's not working or being ignored.

Here is my code:

const mongoose = require('mongoose');
const multer = require('multer');
const uuidV4 = require('uuid/v4');
const Video = require('../models/videoModel');



var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads')
    },


    filename: function (req, file, cb) {
        const newName = uuidV4(); 
        const extension = file.mimetype.split('/')[1];
        cb(null, newName +`.${extension}`)

  },

    fileFilter: function(req, file, cb){

        if(file.mimetype !== 'video/avi'){
          return cb(null, false, new Error('goes wrong on the mimetype'));
        }
        cb(null, true);
    }
})

var upload = multer({ storage: storage });
exports.uploadVideo = upload.single('video');

exports.CreateVideo =  async (req, res, next) => {
    const filePath = req.file.filename;
    const video =  await Video.create({title:req.body.title, path: filePath});
    console.log(video);
};

exports.Home = (req, res) =>{
    res.render('index');
};

Solution

  • fileFilter isn't an storage property, but a multer one.

    function fileFilter(req, file, cb) {
    
        console.log('file filter called')
    
        if (file.mimetype !== 'video/avi') {
            return cb(null, false, new Error('goes wrong on the mimetype'));
        }
        cb(null, true);
    }
    
    var upload = multer({ storage: storage, fileFilter: fileFilter });
    

    Hope it can help.