Why formData does not work with multiple files?
Asked Answered
A

2

15

I'm facing a problem with a React project I'm working on: I'm trying to upload multiple images to a Node Express API. I'm using a formData object and I used the append() method to append the form fields from the component State.

In the Express code I'm using multer, all the attributes in the req.body are there but req.files is empty.

I changed the code to upload a single image also using formData() and it works; the problem seems to be only when I try with multiple files using the formData object. I also tested using a regular form (not react) and that also worked!

I'm wondering if there is something I'm missing when I use formData with a file input with multiple files?

import React, { Component } from "react";
import axios from "axios";

class Form extends Component {
  constructor() {
    super();
    this.state = { images: {} };
  }

  onChangeImages = e => {
    this.setState({ images: e.target.files })
  };

  onSubmit = e => {
    e.preventDefault();

    const { images } = this.state;

    const formData = new FormData();

    formData.append("images", images);

    axios
      .post("/api/post/create", formData)
      .then(res => console.log(res.data))
      .catch(err => console.error(err));
  };

  render() {
    return (
      <form onSubmit={this.onSubmit}>

        <input
          onChange={this.onChangeImages}
          type="file"
          name="images"
          multiple
          accept="image/png, image/jpeg, image/jpg"
        />

        <br />
        <input type="submit" value="Send" />
      </form>
    );
  }
}

export default Form;

Express code

const express = require('express');
const router = express.Router();
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });


router.post('/create', upload.array('images', 2), (req, res) => {
    console.log(req.files);
    console.log(req.body);
    res.status(200).json(req.body);
});


module.exports = router;
Allergic answered 19/1, 2019 at 17:33 Comment(0)
E
37
formData.append("images", images);

You need to append each file in turn. FormData doesn't support a FileList object.

for (let i = 0 ; i < images.length ; i++) {
    formData.append("images", images[i]);
}
Electrocardiograph answered 19/1, 2019 at 17:44 Comment(0)
G
0

Since you are using "upload.array", in the backend side you need something like this

   let arrayImages = [];
     for (let i = 0; i < req.files.length; i++) {
       let k = path.join(req.files[i].filename);
       arrayImages.push(k)
   }

    images: arrayImages,
Goal answered 10/12, 2023 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.