To upload a file in React Js, we can use FormData() api of javascript. We need to create a form with input file field and append the form value into formdata variable. Then we can send it into a POST request. Let’s see this in action.

Code Example

import React from "react";
import axios from "axios";

export default function App() {
  const [uploadFile, setUploadFile] = React.useState();
  const [superHero, setSuperHero] = React.useState();
  const submitForm = (event) => {

    const dataArray = new FormData();
    dataArray.append("superHeroName", superHero);
    dataArray.append("uploadFile", uploadFile);

      .post("api_url_here", dataArray, {
        headers: {
          "Content-Type": "multipart/form-data"
      .then((response) => {
        // successfully uploaded response
      .catch((error) => {
        // error response

  return (
      <form onSubmit={submitForm}>
          onChange={(e) => setSuperHero(}
          placeholder={"Superhero Name"}
        <br />
        <input type="file" onChange={(e) => setUploadFile(} />
        <br />
        <input type="submit" />

Β Β Β Β Tweet this to help others

There are few points about this code –

  1. For network requests I am using Axios library. You can use default fetch functions in its place.
  2. We are sending POST parameter as well as FILE in the same request.
  3. The content-type header is set to multipart/form-data so that file upload can work.
  4. Replace api_url_here with the url on which you want to upload file, like

We have created a form which has 2 fields – text and file. The values of these input fields are stored in state variables – superHero and uploadFile.

Note: For files we are using and for text field,

In our <form> tag, we are calling submitForm() function. Don’t forget to use event.preventDefault() otherwise form will submit in its default html behavior and reload the application.

Next, we created a FormData() variable and append the text field value and file value in it. With the help of Axios, we sent the data to the API.

If you are using php as backend then you can access the data using –

$_POST['superHeroName'] for text field value.

$_FILES['uploadFile'] for file field value.

You may learn more about formdata here. It’s best to use react-native-forms library to create forms in react js.

Live Demo


About the Author


I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles