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) => {
    event.preventDefault();

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

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

  return (
    <div>
      <form onSubmit={submitForm}>
        <input
          type="text"
          onChange={(e) => setSuperHero(e.target.value)}
          placeholder={"Superhero Name"}
        />
        <br />
        <input type="file" onChange={(e) => setUploadFile(e.target.files)} />
        <br />
        <input type="submit" />
      </form>
    </div>
  );
}

    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 https://www.example.com/uploadFile.php

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 e.target.files and for text field, e.target.value

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

Comments

About the Author

akamit

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