How to Create a File Upload System with Laravel and React

Creating a file upload system with Laravel and React involves several steps. Here’s a full breakdown to guide you through the process:

Introduction

File uploads are a common feature in many web applications. This guide will show you how to create a simple file upload system using Laravel as the backend and React as the frontend. We’ll cover setting up the backend endpoint in Laravel, building a React frontend to handle file selection and uploads, and displaying the uploaded files.

Prerequisites

Before you start, ensure you have the following:

  • – Basic knowledge of Laravel and React
  • – A Laravel project set up
  • – A React project set up (e.g., using Create React App)

Step 1: Setting Up Laravel Backend

1. Create a Route and Controller Method

Create a controller if you don’t have one already:

bash
php artisan make:controller FileUploadController

Add the following route in `routes/web.php`:

php
Route::post('/upload', [FileUploadController::class, 'upload']);

2. Create the Upload Method in the Controller
In `FileUploadController.php`, add an `upload` method to handle file uploads:

php
public function upload(Request $request)
{
    // Validate the incoming file
    $request->validate([
        'file' => 'required|file|mimes:jpg,jpeg,png,pdf|max:2048',
    ]);

    // Store the file
    if ($request->file()) {
        $file = $request->file('file');
        $fileName = time() . '_' . $file->getClientOriginalName();
        $filePath = $file->storeAs('uploads', $fileName, 'public');

        // Return a response
        return response()->json(['success' => 'File uploaded successfully', 'path' => '/storage/' . $filePath]);
    }

    return response()->json(['error' => 'File not uploaded'], 400);
}

Step 2: Set Up React Frontend

1. Create a Form Component for File Upload
In your React project, create a new component `FileUpload.js`:

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

const FileUpload = () => {
    const [file, setFile] = useState(null);
    const [message, setMessage] = useState('');

    const handleFileChange = (e) => {
        setFile(e.target.files[0]);
    };

    const handleUpload = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await axios.post('http://localhost:8000/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });
            setMessage(response.data.success || 'File uploaded successfully');
        } catch (error) {
            setMessage('Error uploading file');
        }
    };

    return (
        <div>
            <h2>File Upload</h2>
            <form onSubmit={handleUpload}>
                <input type="file" onChange={handleFileChange} />
                <button type="submit">Upload</button>
            </form>
            <p>{message}</p>
        </div>
    );
};

export default FileUpload;

Step 3: Display Uploaded Files (Optional)

You can extend the functionality to display uploaded files by fetching and rendering a list of files stored on the server.

 

Conclusion

By following these steps, you can quickly build a file upload system using Laravel as the backend and React as the frontend. This setup can be customized to handle different file types, multiple file uploads, and more complex requirements.

 

Read Also :
How to Handle Axios Requests in React with a Laravel API

How JavaScript Modules Work: ES6 Modules and CommonJS

Also Visit :
https://inimisttech.com/

Leave a Reply