Home > Blockchain >  Multer incorrectly parses formData
Multer incorrectly parses formData

Time:09-17

Multer receives the Form Data, but leaves all fields, including the image files, in the req.body object. Here is my code:

React:

const state = {
  // other fields
  images: [], // array of image files
};

let formData = new FormData();
// append other fields
formData.append("images", state.images);

await fetch(url, {
  body: formData,
  // config
});

Express:

const express = require("express");
const router = express.Router();
const controller = require("./controller");
const multer = require("multer");

const storage = multer.memoryStorage();

const imageFilter = (req, file, cb) => {
  // accept image files only
  if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
    return cb(new Error("Only image files are allowed!"), false);
  }
  cb(null, true);
};

const upload = multer({ storage, fileFilter: imageFilter });

// other routes
router.post("/", upload.array("images"), controller.handleImagePost);

CodePudding user response:

Multer doesn't parse the Form Data files if they are nested in an array. It's best to loop over your React state array, and append each file individually to the formData object. (See FormData API and Multer docs)

for (const image of state.images) {
  formData.append("image", image, image.path);
}

Make sure to match the form data field name in your multer middleware code

router.post("/", upload.array("image"), controller.handleImagePost);
  • Related