萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

CodeIgniter 4 檔案上傳類完整教學:驗證、儲存、多檔案與錯誤處理

環境需求

  • CodeIgniter 4.x (Composer 安裝)
  • PHP 7.4+、fileinfo 擴充
  • 寫入權限:writable/uploads/

控制器實作

<?php namespace App\Controllers;

use CodeIgniter\Controller;

class Upload extends Controller
{
    public function index()
    {
        return view('upload_form');
    }

    public function doUpload()
    {
        $files = $this->request->getFiles();
        if (!isset($files['images'])) return redirect()->back()->with('error', '無檔案');

        $results = ['success' => [], 'errors' => []];
        $allowedTypes = ['image/jpeg','image/png','image/gif','image/webp'];
        $maxSize = 5 * 1024 * 1024; // 5MB
        $uploadDir = WRITEPATH . 'uploads/' . date('Y-m-d') . '/';

        foreach ($files['images'] as $file) {
            if ($file->getError() !== UPLOAD_ERR_OK) {
                $results['errors'][] = $file->getClientName() . ': ' . $file->getErrorString();
                continue;
            }
            if ($file->getSize() > $maxSize) {
                $results['errors'][] = $file->getClientName() . ': 檔案過大';
                continue;
            }
            if (!in_array($file->getMimeType(), $allowedTypes)) {
                $results['errors'][] = $file->getClientName() . ': 型別不允許';
                continue;
            }

            $newName = $file->getRandomName(); // 隨機檔名,含副檔名
            if ($file->move($uploadDir, $newName)) {
                $results['success'][] = [
                    'original' => $file->getClientName(),
                    'stored'   => $newName,
                    'path'     => 'uploads/' . date('Y-m-d') . '/' . $newName,
                    'size'     => $file->getSize(),
                ];
            } else {
                $results['errors'][] = $file->getClientName() . ': 移動失敗';
            }
        }

        return $this->response->setJSON($results);
    }
}

視圖 upload_form.php

<form method="post" action="" enctype="multipart/form-data">
    
    <input type="file" name="images[]" multiple accept="image/*" required>
    <button type="submit">上傳</button>
</form>

<script>
document.querySelector('form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const fd = new FormData(e.target);
    const res = await fetch(e.target.action, {method: 'POST', body: fd, headers: {'X-Requested-With': 'XMLHttpRequest'}});
    const data = await res.json();
    data.success.forEach(f => console.log('OK:', f.path));
    data.errors.forEach(err => console.error('ERR:', err));
});
</script>

設定檔 config/Validation.php(集中驗證規則)

public $upload = [
    'images' => [
        'label' => '上傳圖片',
        'rules' => 'uploaded[images]|max_size[images,5120]|mime_in[images,image/jpeg,image/png,image/gif,image/webp]',
    ],
];

控制器可簡化為:if (!$this->validate('upload')) return $this->response->setJSON(['errors' => $this->validator->getErrors()]);

安全與效能補強

  • 掃毒:exec("clamscan {$file->getTempName()}") 非同步處理
  • 圖片處理:Image::withFile($path)->fit(800,600)->save($path) (CodeIgniter Image 擴充)
  • CDN 上傳:移動至 S3/GCS,$file->move($s3Path) 需配合 Flysystem 適配器
  • 資料庫記錄:成功後寫入 attachments 表,關聯業務實體
copyright © 萬盛學電腦網 all rights reserved