Drag and Drop Image and File Upload Using React and Laravel

11 months ago admin Reactjs

In this tutorial, we will see how to upload files using drag and drop in React js and Laravel, first, we will set the frontend using React js, and next, we will set the backend using Laravel.


Install the package

First, let's install the package that we need:

                                                    
                                                                                                                
npm i react-drag-drop-files

Create the upload form

Create a new component inside your react js project 'Upload.jsx' inside we have the form and the upload function once the submit button is clicked we upload the file to the backend.

                                                        
                                                                                                                        
import React, { useState } from 'react'
import { FileUploader } from "react-drag-drop-files"
import axios from 'axios'

export default function Upload() {
    const [picture, setPicture] = useState({
        title: '',
        file: null
    })
    const fileTypes = ["JPG", "PNG", "JPEG"]
    const [fileSizeError, setFileSizeError] = useState('')

    const handleChange = (file) => {
        setFileSizeError('')
        setPicture({
            ...picture, file: file
        })
    }

    const handleSizeError = () => {
        setFileSizeError('The file size must not be greater than 2MB.')
    }

    const storeImage = async (e) => {
        e.preventDefault()
        const formData = new FormData()
        formData.append('file', picture.file)
        formData.append('title', picture.title)

        try {
            const response = await axios.post(`http://127.0.0.1:8000/api/store/picture`,
            formData)
            console.log(response.data.message)
        } catch (error) {
            console.log(error)
        }
    }

    return (
        <div className='container'>
            <div className="row my-5">
                <div className="col-md-6 mx-auto">
                    <div className="card">
                        <div className="crad-header bg-white">
                            <h5 className="text-center mt-4">
                                Upload file
                            </h5>
                        </div>
                        <div className="card-body">
                            <form className='mt-5' onSubmit={(e) => storeImage(e)}>
                                <div className="mb-3">
                                    <label htmlFor="title" 
                                        className='form-label'>Title*</label>
                                    <input type="text" name="title" id="title"
                                        className='form-control'
                                        onChange={(e) => setPicture({
                                            ...picture, title: e.target.value
                                        })}
                                    />
                                </div>
                                <div className='mb-3'>
                                    <FileUploader 
                                        handleChange={handleChange} 
                                        name="file" 
                                        types={fileTypes} 
                                        required={!picture.file}  
                                        maxSize={2} 
                                        onSizeError={handleSizeError}
                                        classes="drop_area"
                                    />
                                    {
                                        fileSizeError && <div className="text-white my-2 rounded p-2 bg-danger">
                                            { fileSizeError }
                                        </div>
                                    }
                                    {
                                        picture?.file && 
                                        <img 
                                            src={URL.createObjectURL(picture.file)}
                                            alt="Picture"
                                            width={150}
                                            height={150}
                                            className="rounded my-2"
                                        />
                                    }
                                </div>
                                <div className="mb-3">
                                    <button type="submit"
                                        className='btn btn-sm btn-dark'>
                                        Submit
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}


Create the controller

Now, let's move to the backend and create the 'UploadController' Inside we add the function that receives and stores the data in the database.

                                                        
                                                                                                                        
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Picture;
use Illuminate\Http\Request;

class UploadController extends Controller
{
    /**
     * Upload files
    */
    public function uploadFile(Request $request)
    {
        //save file
        $file = $request->file('file');
        $file_name = $this->saveImage($file);
        //save the data
        Picture::create([
            'title' => $request->title,
            'file_path' => 'storage/user/images/'.$file_name,
        ]);
        //return the response
        return response()->json([
            'message' => 'Picture has been saved successfully'
        ]);
    }

    /**
     * Save the picture in the storage
    */
    public function saveImage($file)
    {
        $file_name = time().'_'.'picture'.'_'.$file->getClientOriginalName();
        $file->storeAs('user/images', $file_name, 'public');
        return $file_name;
    }
}

Add custom CSS classes to the drop zone

You can customize the size of the drop zone we have already added a 'classes' property to the 'FileUploader' component containing a custom CSS class that we will use.

So inside your 'index.css' file, you can add the following CSS style to make the drop zone size bigger than the default one.

                                                        
                                                                                                                        
.drop_area {
    height: 200px !important;
}


Add routes

Finally, let's add the route:

                                                        
                                                                                                                        
Route::post('store/picture', [UploadController::class, 'uploadFile']);

Related Tuorials

Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 5

In the last part of this tutorial, we will display the cart items, add the ability to increment/decr...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 4

In the fourth part of this tutorial, we will fetch and display all the products on the home page, an...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 3

In the third part of this tutorial, we will start coding the front end, first, we will install the p...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 2

In the second part of this tutorial, we will create the product and payment controllers, and later w...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 1

In this tutorial, we will create a shopping cart using React js Laravel 11 and Stripe payment gatewa...


How to Use Rich Text Editor in React js

In this lesson, we will see how to use rich text editor in React JS, let's assume that we have a com...


How to Download a File from the Server Using Laravel and React js

In this tutorial, we will see how to download a file from the server using Laravel and React js, let...


How to Add a Class on Hover in React js

In this lesson, we will see how to add a class on hover in React js, let's assume that we have a boo...


API Authentication Using Laravel Sanctum and React js Part 3

In the third part of this tutorial, we will register and log in the user, get the access token, and...


API Authentication Using Laravel Sanctum and React js Part 2

In the second part of this tutorial, we will start handling the frontend first, we will create the r...