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>
)
}
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 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.
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
for (let i = 0; i < files.length; i++) {
formdata.append(`images[${i}]`, {
uri: pathOfFile,
name: fileName.jpg,
type: mimeType(eg. "image/jpeg")
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With