CakePHP - 文件上传



为了处理文件上传,我们将使用窗体帮助器。以下是文件上传的一个示例。

示例

在 config/routes.php 文件中进行更改,如下面的程序所示。

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();
});

在 src/Controller/FilesController.php 处创建一个 **FilesController.php** 文件。将以下代码复制到控制器文件中。如果已经创建,则忽略。

在 src/ 中创建 uploads/ 目录。上传的文件将被保存在 uploads/ 文件夹中。

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);
         }
      }
   }
?>

在 src/Template 处创建一个 **Files** 目录,在该目录下创建一个名为 **index.php** 的 **视图** 文件。将以下代码复制到该文件中。

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>";
?>

保存在 uploads/ 文件夹中的文件会列给用户。通过访问以下 URL 来执行上述示例 −

https://127.0.0.1/cakephp4/fileupload −

输出

执行上述代码时,你应该看到以下输出 −

Choose File
广告