How to upload files in React using Axios

Last updated on Oct 9, 2021 by Suraj Sharma



In this tutorial, I will discuss how you can upload documents, images or videos in React using Axios


Consider you have a <Form /> component that contains an input element of type="file" and an upload file button, which uploads the selected file to the server using the Axios post method.


import React from 'react';
import axios from 'axios';

const Form = () => {
  // a local state to store the currently selected file.
  const [selectedFile, setSelectedFile] = React.useState(null);

  const handleSubmit = async(event) => {
    event.preventDefault()
    const formData = new FormData();
    formData.append("selectedFile", selectedFile);
    try {
      const response = await axios({
        method: "post",
        url: "/api/upload/file",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      });
    } catch(error) {
      console.log(error)
    }
  }

  const handleFileSelect = (event) => {
    setSelectedFile(event.target.files[0])
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleFileSelect}/>
      <input type="submit" value="Upload File" />
    </form>
  )
};

export default Form;


Let's break the above solution into multiple steps

  1. First, you create a local React state selectedFile using useState() hook to store the currently selected file,

  2. Second, the handleFileSelect event handler updates the selectedFile value using the setter function setSelectedFile and,

  3. Third, the handleSubmit function handles the post request to upload file using Axios.



Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.