CakePHP 檔案上傳

PHPz
發布: 2024-09-10 17:27:12
原創
632 人瀏覽過

為了進行檔案上傳,我們將使用表單助理。這是文件上傳的範例。

範例

在 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 並在該目錄下建立一個 View 文件,名稱為 index.php。 複製以下程式碼位於該檔案中。

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>";
?>
登入後複製

為使用者列出儲存在 uploads/ 資料夾中的檔案。透過造訪以下 URL 來執行上述範例 -

http://localhost/cakephp4/fileupload -

輸出

當您執行上述程式碼時,您應該看到以下輸出 -

Choose File

以上是CakePHP 檔案上傳的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!