This concise and at-a-glance article shows you how to upload multiple files in React with the help of Axios. The job isn’t too gargantuan and can be done in a few simple steps below (you’ll see both Javascript and TypeScript code snippets in step 3):
1. Install Axios by executing the following command:
npm i axios
2. Implement a form with the enctype attribute set to multipart/form-data, then add a multiple file input element, like so:
<form onSubmit={handleFormSubmit} encType='multipart/form-data'>
<input type='file' name='file' multiple />
<button type='submit'>Submit</button>
</form>
3. Create a handler function that will be called when the form is submitted:
const handleFormSubmit = async (e) => {
// prevent the page from reloading
e.preventDefault();
// construct form data
const formData = new FormData(e.currentTarget);
const files = e.currentTarget.files;
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i]);
}
// make a POST request with Axios
const res = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log(res);
};
If you’re writing code with TypeScript, the handler function will look like this:
const handleFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
// prevent the page from reloading
e.preventDefault();
// construct form data
const formData = new FormData(e.currentTarget);
const files = e.currentTarget.files;
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i]);
}
// make a POST request with Axios
const res = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log(res);
};
That’s it. Further reading:
- React: Show Image Preview before Uploading
- Axios: Passing Query Parameters in GET/POST Requests
- How to fetch data from APIs with Axios and Hooks in React
- React + TypeScript: Using setTimeout() with Hooks
- React + TypeScript: setInterval() example (with hooks)
- React: Using inline styles with the calc() function
You can also check our React category page and React Native category page for the latest tutorials and examples.