CakePHP - File upload



To work on file upload we are going to use the form helper. Here, is an example for file upload.

Example

Make Changes in the config/routes.php file, as shown in the following program.

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('fileupload',['controller'=>'Files','action'=>'index']);
   $builder->fallbacks();
});

Create a FilesController.php file at src/Controller/FilesController.php. Copy the following code in the controller file. Ignore, if already created.

Create uploads/ directory in src/. The files uploaded will be saved in uploads/ folder.

src/Controller/FilesController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\View\Helper\FormHelper;
   class FilesController extends AppController {
      public function index(){
         if ($this->request->is('post')) {
            $fileobject = $this->request->getData('submittedfile');
            $uploadPath = '../uploads/';
            $destination = $uploadPath.$fileobject->getClientFilename();
            // Existing files with the same name will be replaced.
            $fileobject->moveTo($destination);
         }
      }
   }
?>

Create a directory Files at src/Template and under that directory create a View file called index.php. Copy the following code in that file.

src/Template/Files/index.php

<?php
   echo $this->Form->create(NULL, ['type' => 'file']);
   echo $this->l;Form->file('submittedfile');
   echo $this->Form->button('Submit');
   echo $this->Form->end();
   $uploadPath ='../uploads/';
   $files = scandir($uploadPath, 0);
   echo "Files uploaded in uploads/ are:<br/>";
   for($i = 2; $i < count($files); $i++)
      echo "File is - ".$files[$i]."<br>";
?>

The files saved in uploads/ folder is listed for the user. Execute the above example by visiting the following URL −

http://localhost/cakephp4/fileupload −

Output

When you execute the above code, you should see the following output −

Choose File
Advertisements