Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 166.8MB ·虚拟内存 1438.9MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
为了处理文件上传,我们将使用表单助手。这是一个文件上传示例。
在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/文件夹中。
<?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> 在该文件中复制以下代码。
<?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 执行上述示例:
http://localhost/cakephp4/fileupload:
当你执行上面的代码时,你应该看到下面的输出: