Uploading File from a React Component

There are multiple ways to upload a file using React. I’m going to explain the steps to upload a single file in React.

To upload a file from a React component, we can use the HTML input element with type="file"

Let's start our today's lesson-

Table of Contents

  1. Create a new React component called FileUploader
  2. Create the upload function
  3. Final component with the api response

Create a new React component called FileUploader

At first, we will create a new React component called FileUploader:

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

function FileUploader() {
    const [file, setFile] = useState(null);

    function handleFileInputChange(event) {
        const selectedFile = event.target.files[0];
        setFile(selectedFile);
    }

    return (
        <form>
            <input type="file" onChange={handleFileInputChange} />
            <button type="submit">Upload</button>
        </form>
    );
}

export default FileUploader;

Here, we have a state named file. We will use setFile to update our state. In the component's handleFileInputChange function, we use the event.target.files property to get the selected file and update the state with the selected file using setFile

Create the upload function

Now we will create our function handleSubmit-

handleSubmit()
function handleSubmit(event) {
        event.preventDefault();
        if (file) {
            const formData = new FormData();
            formData.append('file', file);

            fetch('/api/upload', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    console.log('Upload successful!');
                    console.log(data);
                })
                .catch(error => {
                    console.error('Error uploading file:', error);
                });
        }
    }

Here-

  • We first prevent the default form submission behavior using event.preventDefault()
  • Check if a file has been selected (if (file)), 
  • Then create a new FormData object, 
  • After that we append the selected file to the form data using formData.append('file', file), and finally make a fetch request to the server. We're assuming that the server endpoint for handling file uploads is /api/upload.
  • In the fetch request, we set the method to 'POST', and set the body to the FormData object we created earlier. We also specify that the response should be parsed as JSON using the response.json() method.
  • If the fetch request is successful, we log a success message and the response data to the console using console.log(). If the fetch request fails, we log an error message and the error object to the console using console.error().

There are two things you need to remember when POSTing a file object:

  • Never set the Context-Type Header.
  • Pass the whole FomData object to the body of the request.

Final component with the api response

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

function FileUploader() {
    const [file, setFile] = useState(null);

    function handleFileInputChange(event) {
        const selectedFile = event.target.files[0];
        setFile(selectedFile);
    }

    function handleSubmit(event) {
        event.preventDefault();
        if (file) {
            const formData = new FormData();
            formData.append('file', file);

            fetch('/api/upload', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    console.log('Upload successful!');
                    console.log(data);
                })
                .catch(error => {
                    console.error('Error uploading file:', error);
                });
        }
    }

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

export default FileUploader;

Note that this is just an example, and the server endpoint for handling file uploads (/api/upload) and the response format may vary depending on your specific use case.

Thank you for following along ☺️