Multiple file upload with reactjs

farooq picture farooq · Dec 23, 2019 · Viewed 23.8k times · Source

I'm new to reactjs and I'm trying to upload multiple file upload. I can able to store the files in state component as array . But When I'm passing the data to axios post method, it gives me the list of files as [object FileList] . And I couldn't able to traverse through that files to store . Even I tried multiple methods to upload multiple files like 'react-Dropzone`. But didn't help.

My react Code .

handleChange(event) {
  this.setState({ file: event.target.files })
}

async handleSubmit(e) {
  e.preventDefault()
  let res = await this.uploadFile(this.state.file);
}

async uploadFile(File){
  const formData = new FormData();

  formData.append('image', File)
  axios.post(UPLOAD_ENDPOINT, formData, {
    headers: {
      'content-type': 'multipart/form-data'
    }
  }).then(response => {
    console.log(response.data)
  });
}

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <input type="file" id="file" multiple name="file" onChange={this.handleChange} />
      <button type="submit" className="btn btn-info"> Update File </button>
    </form>
  )
}

Answer

Saud Qureshi picture Saud Qureshi · Dec 23, 2019

The

event.target.files

Will give you a file list, and to append it to form data use the following code.

const files = event.target.files;

for (let i = 0; i < files.length; i++) {
    formData.append(`images[${i}]`, files[i])
}

On the server side you will get all the images from 'images' key of request object/variable