📜  CakePHP-文件上传

📅  最后修改于: 2020-10-26 05:19:04             🧑  作者: Mango


要进行文件上传,我们将使用表单助手。这是文件上传的示例。

更改config / routes.php文件,如以下程序所示。

config / routes.php

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 /目录。上载的文件将保存在上载/文件夹中。

src / Controller / FilesController.php

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.phpView文件将以下代码复制到该文件中。

src /模板/文件/index.php

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-

输出

当执行上述代码时,您应该看到以下输出-

选择文件