CakePHP 4 Drag and Drop File Upload Using Dropzone

Reading Time: 8 minutes
2,759 Views

In many applications, you have been observed file upload process is bit attractive. Inside this article we will see the concept of CakePHP 4 drag and drop file upload using dropzone jquery plugin.

Dropzone.js is a jquery plugin, dropzone.js through we can select one by one image and also with preview.

Uploading files in application using dropzone plugin is super easy. This tutorial is very interesting and easy to learn. We will code in CakePHP for image upload at server.

We can upload any type of file using dropzone but for this tutorial we will use the feature to upload only images via dropzone jquery plugin.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE mydatabase;

Successfully, we have created a database.

Database Connection

Open app_local.php file from /config folder. Search for Datasources. Go to default array of it.

You can add your connection details here to connect with your database. It will be like this –

//...

'Datasources' => [
        'default' => [
            'host' => 'localhost',
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',

            'username' => 'root',
            'password' => 'sample@123',

            'database' => 'mydatabase',
            /*
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
             */
            //'schema' => 'myapp',

            /*
             * You can use a DSN string to set the entire configuration
             */
            'url' => env('DATABASE_URL', null),
        ],
  
     //...

//...

You can pass host, username, password and database.

Successfully, you are now connected with the database.

Create Migration

Open project into terminal and run this command to create migration file.

$ bin/cake bake migration CreateImageUploads

It will create 20220330143909_CreateImageUploads.php file inside /config/Migrations folder. Open migration file and write this following code into it.

The code is all about for the schema of image_uploads table.

<?php

declare(strict_types=1);

use Migrations\AbstractMigration;

class CreateImageUploads extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('image_uploads');
        $table->addColumn("filename", "text", [
            "null" => false
        ]);
        $table->create();
    }
}

Run Migration

Back to terminal and run this command.

$ bin/cake migrations migrate

It will create image_uploads table inside database.

Create Model & Entity

Next,

We will create model and entity. Back to terminal and run this command.

$ bin/cake bake model ImageUploads --no-validation --no-rules

It will create model file ImageUploadsTable.php inside /src/Model/Table folder. Also we should see the entity file ImageUpload.php inside /src/Model/Entity folder.

Create Controller

Again,

Back to terminal and run this command into it.

$ bin/cake bake controller Dropzone --no-actions

It will create DropzoneController.php file inside /src/Controller folder. Open controller file and write this code into it.

<?php

declare(strict_types=1);

namespace App\Controller;

class DropzoneController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel("ImageUploads");
    }

    public function dropzone()
    {
        $uploadObject = $this->ImageUploads->newEmptyEntity();

        if ($this->request->is("post")) {

            $image = $this->request->getData('file');
            $hasFileError = $image->getError();

            if ($hasFileError > 0) {
                // no file uploaded
                $data["filename"] = "";
            } else {
                // file uploaded
                $fileName = str_replace(" ", "-", $image->getClientFilename());
                $fileType = $image->getClientMediaType();

                if ($fileType == "image/png" || $fileType == "image/jpeg" || $fileType == "image/jpg") {
                    $imagePath = WWW_ROOT . "img/" . $fileName;
                    $image->moveTo($imagePath);
                    $data["filename"] = "img/" . $fileName;
                }
            }

            $uploadObject = $this->ImageUploads->patchEntity($uploadObject, $data);

            if ($this->ImageUploads->save($uploadObject)) {
                echo json_encode(["status" => 1, "message" => "Uploaded"]);
            } else {
                echo json_encode(["status" => 0, "message" => "Failed to upload"]);
            }
        }

        $this->set(compact("uploadObject"));
    }
}

Concept of Image Upload

Here, is the code snippet of image upload in above code of controller.

$image = $this->request->getData('file');
$hasFileError = $image->getError();

if ($hasFileError > 0) {
    // no file uploaded
    $data["filename"] = "";
} else {
    // file uploaded
    $fileName = str_replace(" ", "-", $image->getClientFilename());
    $fileType = $image->getClientMediaType();

    if ($fileType == "image/png" || $fileType == "image/jpeg" || $fileType == "image/jpg") {
        $imagePath = WWW_ROOT . "img/" . $fileName;
        $image->moveTo($imagePath);
        $data["filename"] = "img/" . $fileName;
    }
}

WWW_ROOT . “img/” returns the path upto of /img folder of webroot.

Once we drag and drop image it will upload images into /webroot/img folder.

Create Template

Create Dropzone folder inside /templates folder. Next, needs to create dropzone.php file inside /templates/Product folder.

Open dropzone.php file and write this following code into it. This will give the frontend layout for form.

<!DOCTYPE html>
<html>

<head>
    <title>CakePHP 4 Drag And Drop File Upload Using Dropzone - Online Web Tutor</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/dropzone.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/min/dropzone.min.js"></script>
</head>

<body>

    <div class="container section">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <h3 class="text-center">CakePHP 4 Drag And Drop File Upload Using Dropzone</h3>
                <?= $this->Form->create($uploadObject, [
                    "enctype" => "multipart/form-data",
                    "id" => "image-upload",
                    "class" => "dropzone"
                ]) ?>
                <div>
                    <h3 class="text-center">Upload Multiple Image By Click On Box</h3>
                </div>
                <?= $this->Form->end() ?>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        Dropzone.options.imageUpload = {
            maxFilesize: 1,
            acceptedFiles: ".jpeg,.jpg,.png,.gif",
        };
    </script>
</body>

</html>

Disable CSRF Token

When we submit a cakephp form, it needs a CSRF token should be submitted with form submission request.

We are not interested to send CSRF token with form data. To disable it, Open Application.php from /src folder.

Remove these lines of code from middleware() method.

->add(new CsrfProtectionMiddleware([
    'httponly' => true,
]))

Add Route

Open routes.php file from /config folder. Add this route into it.

//...

$routes->connect(
    '/dropzone',
    ['controller' => 'Dropzone', 'action' => 'dropzone']
);

//...

Application Testing

Open terminal and run this command to start development server.

$ bin/cake server

URL: http://localhost:8765/dropzone

This is the view we will get before upload.

Let’s upload few images by dragging and dropping into area.

Data has been saved to database table as well.

We hope this article helped you to learn about CakePHP 4 Drag and Drop File Upload Using Dropzone Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more