React Upload Multiple Files using Axios + PHP Server with Error Handling

React is a popular JavaScript library for building user interfaces, and one common use case is allowing users to upload multiple files to a server. In this tutorial, we will walk through the process of building a simple React application that allows users to select and upload multiple files to a server using Axios and PHP. We will also cover error handling to ensure that the file upload process is smooth and reliable.

 

Prerequisites

Before getting started with this tutorial, you should have a basic understanding of React and JavaScript. You should also have a local development environment set up with Node.js and npm (or yarn) installed. Additionally, you should have a basic understanding of PHP and be familiar with setting up a local development server.

 

Setting up the React Project

First, let’s create a new React project using create-react-app. Open a command prompt or terminal window and run the following command:

npx create-react-app react-file-upload

This will create a new directory called react-file-upload with the basic structure of a React application. Next, navigate into the new project directory and install the axios library, which we will use to make the file upload requests to the server.

cd react-file-upload
npm install axios

Building the File Upload Component

Now that we have a new React project set up, let’s create a new component called FileUpload that will handle the file selection and upload process.

In the src folder, create a new file called FileUpload.js. Inside this file, we will import the useState and useEffect hooks from React, as well as the axios library. We will also create a new component called FileUpload that will render a file input element and a submit button.

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

function FileUpload() {
  const [files, setFiles] = useState([]);
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const [uploadError, setUploadError] = useState(null);

  const handleFileSelection = event => {
    setFiles(event.target.files);
  };

  const handleUpload = async event => {
    event.preventDefault();
    const formData = new FormData();

    for (const file of files) {
      formData.append('files[]', file);
    }

    try {
      const response = await axios.post('/upload.php', formData);
      setUploadedFiles(response.data);
    } catch (error) {
      setUploadError(error);
    }
  };

  return (
    <form onSubmit={handleUpload}>
      <input type="file" multiple onChange={handleFileSelection} />
      <button type="submit">Upload</button>
      {uploadError && <p>{uploadError.message}</p>}
      {uploadedFiles.length > 0 && (
        <ul>
          {uploadedFiles.map(file => (
            <li key={file.name}>{file.name}</li>
          ))}
        </ul>
      )}
    </form>
  );
}

export default FileUpload;

In the code above, we have defined a FileUpload component that renders a file input element and a submit button. The handleFileSelection function is called when the user selects one or more files, and it updates the files state variable with the selected files. The handleUpload function is called when the user submits the form, and it uses the axios library to send a POST request to the server containing the selected files.

 

Setting up the PHP Server

Now that we have the React client set up, let’s create a simple PHP server that can handle file uploads.

Create a new directory called server in the root of your project, and create a new file called upload.php inside it. This file will handle the file uploads from the React client.

<?php

$uploadedFiles = [];

if (isset($_FILES['files'])) {
    $errors = [];
    $path = 'uploads/';
    $all_files = count($_FILES['files']['tmp_name']);

    for ($i = 0; $i < $all_files; $i++) {
        $file_name = $_FILES['files']['name'][$i];
        $file_tmp = $_FILES['files']['tmp_name'][$i];
        $file_type = $_FILES['files']['type'][$i];
        $file_size = $_FILES['files']['size'][$i];
        $file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));

        $extensions = array("jpeg", "jpg", "png");

        if (in_array($file_ext, $extensions) === false) {
            $errors[] = "Extension not allowed, please choose a JPEG or PNG file.";
        }

        if ($file_size > 2097152) {
            $errors[] = 'File size must be less than 2 MB';
        }

        if (empty($errors)) {
            move_uploaded_file($file_tmp, $path . $file_name);
            $uploadedFiles[] = array(
                'name' => $file_name,
                'type' => $file_type,
                'size' => $file_size
            );
        }
    }

    if ($errors) {
        http_response_code(400);
        echo json_encode(array('errors' => $errors));
    } else {
        echo json_encode(array('files' => $uploadedFiles));
    }
}

The code above checks if the files array is set, and if so, it loops through the uploaded files, checking for errors such as invalid file type or size. If there are no errors, the files are moved to the uploads directory, and their details are added to the $uploadedFiles array. If there are errors, the server returns a 400 Bad Request status code and the errors in JSON format.

 

Testing the File Upload

To test the file upload, you will need to run both the React development server and the PHP server.

In the root of your project, start the React development server by running the following command:

npm start

This will start the development server and open a browser window with the application running at http://localhost:3000.

In a separate terminal window, navigate to the server directory and start the PHP server using a tool such as XAMPP or MAMP. Once the PHP server is running, you can test the file upload by selecting one or more files in the file input element and clicking the submit button. The uploaded files should be saved in the uploads directory and the file details should be displayed on the page.

 

Error Handling

As shown in the FileUpload component, we also added error handling. If an error occurs during the file upload, the uploadError state variable is updated with the error, and the error message is displayed on the page.

It is also important to note that, in the PHP server code, we are returning the error response with a HTTP status code of 400. This makes it easy for the React application to identify the error, and handle it accordingly.

 

Conclusion

In this tutorial, we have covered how to build a simple React application that allows users to select and upload multiple files to a server using Axios and PHP. We have also covered error handling to ensure that the file upload process is smooth and reliable.

While this example is relatively simple, it can be easily extended to include features such as progress indicators, validation, and security measures such as authentication and authorization.

Leave a Comment

Your email address will not be published. Required fields are marked *