CakePHP - File upload


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


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


use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);

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.


   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.

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.


   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 −


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

Choose File