Drag and Drop Image and File Upload Using React and Laravel

3 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

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...


API Authentication Using Laravel Sanctum and React js Part 1

In today's tutorial, we are going to see how to create a token-based authentication system using Lar...


How to Update Nested Array with Hooks in React

In this lesson, we will see how to update nested array with hooks in React, let's assume that we hav...


How to Set the Loading State Only on a Specific Clicked Button in React

In this lesson, we will see how to set the loading state only on a specific clicked button in React,...


Create a Rest API in PHP and Consume it in React Part 5

In the fifth part of this tutorial, we will add routes to our application and finally, we will add s...


Create a Rest API in PHP and Consume it in React Part 4

In the fourth part of this tutorial, we are going to create the frontend using react and consume the...