Understanding React File Upload

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

File Upload Process in React

Uploading files in a React app, such as images, documents, or any other file types, typically follows a structured approach:

User File Selection

The journey begins by allowing the user to select a file. In React, this is commonly achieved by utilizing the <input> element with its type attribute set to “file”. This offers a user-friendly interface for file selection. When a file is chosen, it’s important to have an event handler in place. This event handler listens to any changes or interactions with the file input and updates the application’s state with the selected file’s information.

Server Communication

Once the file information is captured and stored in the application’s state, the next pivotal step is sending it over to a server. This could be for processing, storage, or any other backend operation. Tools like axios or the native fetch API are frequently employed to handle this communication. They aid in making asynchronous HTTP requests to servers. It’s crucial to wrap the selected file in a FormData object, ensuring the data is properly formatted for transmission.

Feedback & Response Handling

Upon initiating communication with the server, always anticipate two outcomes: success or failure. Implementing feedback mechanisms like success messages, error alerts, or even displaying the uploaded file helps improve user experience. It provides assurance that their action (file upload) was successful or gives clarity if something goes amiss.

Error Handling

The digital realm isn’t always predictable. Issues might arise during the upload process, be it network glitches, file format mismatches, or server-side errors. Being prepared with a robust error-handling mechanism not only aids in troubleshooting but also ensures users aren’t left in the dark. Informative error messages and alternative solutions can steer users in the right direction.

External Libraries and Tools

While React provides a solid foundation, sometimes external libraries or tools can expedite the development process. Tools like axios simplify HTTP communications. Moreover, services like Filestack offer out-of-the-box file-uploading solutions, saving development time.

By adhering to this structured approach, developers can ensure a smooth and efficient file upload process in their React applications, enhancing both functionality and user satisfaction.

Now, let’s dive into the nitty-gritty details.

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 chooses 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 an 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:5168/api/FileUpload/upload';
    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileName', file.name);
    axios.post(url, formData).then((response) => {
      console.log(response.data);
    })
       .catch((error) => {
        console.error("Error uploading file: ", error);
      });

  }

  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;

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:5168/api/FileUpload/upload.

Upload file

API Controller

Console