codewithjohn.dev
Published on

How to Upload Files With React

Introduction

React is a popular JavaScript library used for building user interfaces. In this article we are going to explore how to implement file upload react application. we will cover both uploading single file and uploading multiple Files and also how to send the file to server. When it comes to file uploads in React, there are a few steps involved.

  1. First, you need to create an input field with type file in your React component. when the users selects a file you can capture that file using an event handler function. and use the onChange event to trigger the to trigger this function.

  2. In the event handler function, you can access the selected file using the event.target.files property which is a FileList object. Each item in the FileList is a File object. .For Example You can access the first file using event.target.files[0]. Ones you get the selected files you can store them in a react state

  3. Once you have the file in the state before sending the file to the server you can performe validation such as checking the file type, size, or applying any required transformations.

  4. Finally, you can send the file to the server for processing. For this purpose, we can use fetch or Axios.

Uploading a single file

Here's an example:

import React, { useState } from 'react'

function FileUpload() {
  const [selectedFile, setSelectedFile] = useState(null)

  const handleFileChange = (event) => {
    setSelectedFile(event.target.files[0])
  }

  return (
    <div>
      <input type="file" onChange={handleFileChange} />
      <button onClick={handleFileUpload}>Upload</button>
    </div>
  )
}

Multiple File Upload

Let's modify the previous example slightly. instaed of storing single file in the state we can store array of files and add multiple attribute to the html input element.

Here's an updated version:

import React, { useState } from 'react'

function MultipleFileUpload() {
  const [selectedFiles, setSelectedFiles] = useState([])

  const handleFileChange = (event) => {
    setSelectedFiles(event.target.files)
  }

  const handleFileUpload = () => {
    // handle file upload logic
  }

  return (
    <div>
      <input type="file" multiple onChange={handleFileChange} />
      <button onClick={handleFileUpload}>Upload</button>
    </div>
  )
}

Uploading Files to a Server

To complete the file upload process, we need to send the file(s) to a server using an HTTP request. For simplicity, we will demonstrate this using the popular Axios library.

Here's an example:

import React, { useState } from 'react'
import axios from 'axios'

function UploadToServer() {
  const [selectedFile, setSelectedFile] = useState(null)

  const handleFileChange = (event) => {
    setSelectedFile(event.target.files[0])
  }

  const handleFileUpload = () => {
    const formData = new FormData()
    formData.append('file', selectedFile)

    axios
      .post('/upload', formData)
      .then((response) => {
        // handle success
      })
      .catch((error) => {
        // handle error
      })
  }

  return (
    <div>
      <input type="file" onChange={handleFileChange} />
      <button onClick={handleFileUpload}>Upload</button>
    </div>
  )
}