React: How to Upload Multiple Files with Axios

Updated: March 2, 2023 By: Snowball Post a comment

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:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles