Search code examples
reactjsreact-nativereact-routermultiple-file-upload

Multiple file upload with reactjs


I'm new to reactjs and I'm trying to upload multiple files. I can store the files in state component as an 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 traverse through the files to store. I even tried multiple methods to upload multiple files like 'react-Dropzone` but it 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>
  )
}

Solution

  • 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