0
votes

I'm trying to upload a picture where the user registers in the app. When I'm trying to test it in insomnia I get the following error: MulterError: Unexpected field at wrappedFileFilter

I've been reading online and I know this error occurs when there is a mismatch between the field name provided by the client and the field name expected by the server. However, I've been checking many times my code and the name that I give in the server and the client (Insomnia) is the same: "image". Any idea what else can I try?

Here is my code:

const storage = multer.diskStorage({
    destination: './client/public/img',
    filename: (req, file, cb) => {
        console.log(file)
        cb(null, file.originalname)
    }
})

const fileFilter = (req, file, cb) => {
    if(file.mimetype == "image/jpeg" || file.mimetype == "image/png") {
        cb(null, true)
    } else {
        cb(null, false)
    }
}

const upload = multer({ storage: storage, fileFilter: fileFilter, destination: './client/public/img' })
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

//sign up
routes.post("/register", upload.single("image"), (req, res) => {
    let { user_name, email, password, password2 } = req.body;
    let { image } = req.file.filename
    let errors = []

    //check required inputs
    if(!user_name || !email || !password || !password2){
        errors.push({message: "Please fill all required fields"})
        res.send({message: "Please fill all required fields"})   
    }

    //check passwords
    if(password != password2) {
        errors.push({message: "Passwords do not match"})
        res.send({message: "Passwords do not match"})
    }

    if(errors.length>0) {
        console.log(errors);
    } else {
        if(email) {
            db(`SELECT * FROM user WHERE email = "${email}"`)
            .then((results) => {
                if(results.data.length>0){
                    res.send("Email exists")
                } else {
                    bcrypt.hash(password, saltRounds, (err, hash) => {
                    password = hash
                    db(`INSERT INTO user (user_name, email, password, image) VALUES ("${user_name}", "${email}", "${password}", "${image}")`)
                        .then((results) => {
                            res.send("Registration successful")
                            if(err)throw err;
                        })
                        .catch((error) => {
                            console.log(error)
                        })
                    })
                }
            })
            .catch((error) => {
                console.log(error)
            })
        } else {
            res.send("Enter email")
        }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Any help will be appreciated. Thanks in advance.

1
How you are uploading your file? is the name attribute image the same in your upload.single() method?rags2riches
Ahhhh you have given me the key!! I'm so dumb! I was writing "image" instead of image, it works now. Now I have to deal with another error, but the image is stored correctly. Thanks.Guerreri88
I am glad the answer helped you ?rags2riches

1 Answers

1
votes

I am making the assumption that you are using form to upload your file. If, so...

Front end snippet:

<form action="/register" method="post" enctype="multipart/form-data">
  <input type="file" name="image" />
</form>

Get multer to upload the file correctly:

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './client/public/img')
  },
  filename: function (req, file, cb) {
    if(file.mimetype == "image/jpeg" || file.mimetype == "image/png") {
      cb(null, file.fieldname + '-' + Date.now());
    } 
    else {
     cb(new MulterError('LIMIT_UNEXPECTED_FILE', file.fieldname));
    }
});
 
const upload = multer({ storage: storage });

Handle the error inside your Express middleware by calling upload as below...

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }
 
    // Everything went fine.
  })
})