I want to upload a file with other form data. but when i upload file with different route like router.post(/api/upload)" it works, but i want to upload file along with other form data to route like route.post('/api/complaints') etc. but when i do with route.post('/api/complaints'), the "req.file" is undefined but when i do with router.post(/api/upload), it gets uploaded. Please help.

this is multer configuring

const upload = multer({
  limits: {
    fileSize: 10000000
  fileFilter(req, file, cb) {
    if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
      return cb(new Error("File must be .jpg | .jpeg | .png"));
    cb(undefined, true);

this is the route for uploading file.

  async (req, res) => {
    // req.file.buffer;
    res.status(200).send("file uploaded successfully." + req.file.buffer);
  (error, req, res, next) => {
    res.status(400).send({ error: error.message });

this is the route for posting all form data. Problem is here. here req.file is undefined.

  async (req, res) => {

    const category = await Category.findById(req.body.categoryId);

    if (!category) return res.status(400).send("Invalid category.");

    const assignee = await Assignee.findOne({
      responsibility: category
    if (!assignee) return res.status(400).send("Invalid Assignee.");

    const complainer = await Complainer.findById(req.complainer._id);
    if (!complainer) return res.status(400).send("Invalid Complainer.");

    let complaint = new Complaint({
      category: {
        _id: category._id
      complainer: {
        _id: complainer._id
      assignedTo: {
        _id: assignee._id
      geolocation: req.body.geolocation ? req.body.geolocation : "",
      details: req.body.details,
      title: req.body.title,
      location: req.body.location,
      image: req.file ? req.file.buffer : ""

    await complaint.save();

this is my reactjs code

 handleFileChange = e => {
    // if (this.checkMimeType(e)) {
    this.setState({ selectedFile: e.target.files[0] });

doSubmit = async () => {
    this.setState({ isDialogOpen: false });
    this.setState({ isLoading: true });

    const data = new FormData();

    const newState = { ...this.state.data, data };

    const { data: result } = await saveComplaint(this.state.data);
    this.setState({ isLoading: false });

    toast.success("Complaint is successfully registered.");
    // this.props.history.replace("/complainer");

i want to upload file along with other form data like input type text etc but its not working. please help. The main problem is in React.js code. req.file is undefined when sent from React app. when i tested it from Postmon. it works on both scenarios

1 Answers

AlainD. On

So, if you already identified that "the issue if in React.js", then file an issue in React’s github instead!