CakePHP 文件上传

cakephp 文件上传

 

为了处理文件上传,我们将使用表单助手。这是一个文件上传示例。

 

示例

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

 

config/routes.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

   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 的 view 文件。 b> 在该文件中复制以下代码。

 

src/template/files/index.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:
";
   for($i = 2; $i < count($files); $i++)
      echo "file is-".$files[$i]."
";
?>

为用户列出了保存在uploads/文件夹中的文件。通过访问以下 url 执行上述示例:

http://localhost/cakephp4/fileupload:

 

输出

当你执行上面的代码时,你应该看到下面的输出:

相关文章