Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple file upload with reactjs

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>
  )
}
like image 776
farooq Avatar asked Dec 23 '19 07:12

farooq


People also ask

How do I select multiple files in React?

To enable multiple file selection with the file input with React, we can add the multiple prop to the file input. We have a file input which we create by setting the type attribute to file . And we add the multiple prop to it to make it allow multiple file selection.

How do I send multiple files in FormData in React JS?

How to Upload Multiple Files in React using FormData. When we need to upload multiple files using Fetch, we have to use a new type of object called FormData. FormData allows us to append multiple key/value pairs onto the object. After we're done appending, we then pass it to the POST request's body.


2 Answers

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

like image 135
Saud Qureshi Avatar answered Sep 25 '22 17:09

Saud Qureshi


for (let i = 0; i < files.length; i++) { 
    formdata.append(`images[${i}]`, {
                    uri: pathOfFile,
                    name: fileName.jpg,
                    type: mimeType(eg. "image/jpeg")
    });
}
like image 26
Shubham Sharma Avatar answered Sep 21 '22 17:09

Shubham Sharma