React File Upload

Welcome to our React file upload tutorial. In this article, we’ll cover how to enable file uploads in your React app from scratch. If you want a simple plug & play solution, try our React Filepicker Component (you’ll need to create a free Filestack account to get your API key).

We’re starting with a freshly created react app with the default content removed.

import './App.css';

function App() {
  return (
    <div className="App">

    </div>
  );
}

export default App;

The first thing we’ll do is create a simple form where our user can choose what file to upload.

import './App.css';
function App() {
  return (
    <div className="App">
        <form>
          <h1>React File Upload</h1>
          <input type="file" />
          <button type="submit">Upload</button>
        </form>
    </div>
  );
}

export default App;

Next, we’ll create a state variable, add an onChange event handler to the input element, and create a handleChange function to keep track of what file our user chose to upload.

import './App.css';
import React, {useState} from react;

function App() {

  const [file, setFile] = useState()

  function handleChange(event) {
    setFile(event.target.files[0])
  }

  return (
    <div className="App">
        <form>
          <h1>React File Upload</h1>
          <input type="file" onChange={handleChange}/>
          <button type="submit">Upload</button>
        </form>
    </div>
  );
}

export default App;

Now that we know what file our user chose to upload, we’ll add axios for making http requests, an onSubmit event handler to the form, and a handleSubmit function to upload the file using a http POST request.

import './App.css';
import React, {useState} from 'react';
import axios from 'axios';

function App() {

  const [file, setFile] = useState()

  function handleChange(event) {
    setFile(event.target.files[0])
  }
  
  function handleSubmit(event) {
    event.preventDefault()
    const url = 'http://localhost:3000/uploadFile';
    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileName', file.name);
    const config = {
      headers: {
        'content-type': 'multipart/form-data',
      },
    };
    axios.post(url, formData, config).then((response) => {
      console.log(response.data);
    });

  }

  return (
    <div className="App">
        <form onSubmit={handleSubmit}>
          <h1>React File Upload</h1>
          <input type="file" onChange={handleChange}/>
          <button type="submit">Upload</button>
        </form>
    </div>
  );
}

export default App;

This is the critical step for enabling file uploads. We’ve created a config object to specify a ‘content-type’ header for our http request. In order to upload files, the ‘content-type’ header must be set to ‘multipart/form-data’.

new FormData() creates a new empty formData object that we send as the payload in our POST request. Our POST request assumes there is an API endpoint on our backend server at http://localhost:3000/uploadFile.

We’re done! If you want to learn about how to setup the backend server that would receive the POST request we made in this article, check out our articles on how to upload a file using NodeJS (or with Python if you prefer).

If you don’t want to go through the trouble of setting up a server, consider signing up for a free Filestack account and using our file upload SDKs & APIs to add file uploading functionality to your app with just 2 lines of code.

 


Read More →

Ready to get started?

Create an account now!