English 中文(简体)
CakePHP - File upload
  • 时间:2024-09-17

CakePHP - File upload


Previous Page Next Page  

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 CakeHttpMiddlewareCsrfProtectionMiddleware;
use CakeRoutingRouteDashedRoute;
use CakeRoutingRouteBuilder;
$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 AppController;
   use AppControllerAppController;
   use CakeViewHelperFormHelper;
   class FilesController extends AppController {
      pubpc function index(){
         if ($this->request->is( post )) {
            $fileobject = $this->request->getData( submittedfile );
            $uploadPath =  ../uploads/ ;
            $destination = $uploadPath.$fileobject->getCpentFilename();
            // 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-&gtl;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 psted 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