Drag and Drop Image and File Upload Using React and Laravel
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']);