萬盛學電腦網

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

Yii 2.0 文件上傳完整實戰:從表單到控制器的最佳實踐

Yii 2 內建 yii\web\UploadedFile 類封裝了文件上傳的完整流程。本文提供從 View 表單構建、Controller 處理、驗證規則、安全防護、多文件上傳到雲存儲擴展的完整最佳實踐指南。

1. View 層:構建上傳表單

<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use yii\helpers\Url;

/* @var $model app\models\UploadForm */
?>
'upload-form', 'options' => ['enctype' => 'multipart/form-data'], // 關鍵:啟用文件上傳 'action' => Url::to(['site/upload']), ]); ?> field($model, 'imageFile')->fileInput(['accept' => 'image/*']) ?> field($model, 'category')->dropDownList([ 'avatar' => '頭像', 'document' => '文檔', 'gallery' =>相冊', ]) ?>
'btn btn-primary', 'name' => 'upload-button']) ?>

2. Model 層:驗證規則封裝

<?php
namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

class UploadForm extends Model {
    public UploadedFile|null $imageFile = null;
    public string $category = 'gallery';
    
    // 上傳配置
    public const MAX_SIZE = 5 * 1024 * 1024;  // 5MB
    public const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    public const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    
    // 目錄映射
    public const CATEGORY_DIRS = [
        'avatar' => 'avatars',
        'document' => 'documents',
        'gallery' => 'gallery',
    ];

    public function rules(): array {
        return [
            [['imageFile'], 'required', 'message' => '請選擇要上傳的文件'],
            [['imageFile'], 'file', 
                'skipOnEmpty' => false,
                'extensions' => self::ALLOWED_EXTENSIONS,
                'mimeTypes' => self::ALLOWED_MIME_TYPES,
                'maxSize' => self::MAX_SIZE,
                'tooBig' => '文件大小不能超過 5MB',
                'wrongExtension' => '僅支持 {extensions} 格式',
                'wrongMimeType' => '文件類型不允許',
            ],
            [['category'], 'in', 'range' => array_keys(self::CATEGORY_DIRS)],
        ];
    }

    /** 上傳處理核心邏輯 */
    public function upload(): array {
        if (!$this->validate()) {
            return ['success' => false, 'message' => '驗證失敗: ' . json_encode($this->getFirstErrors())];
        }

        $dirName = self::CATEGORY_DIRS[$this->category] ?? 'others';
        $basePath = Yii::getAlias('@webroot/uploads/' . $dirName);
        
        // 確保目錄存在
        if (!is_dir($basePath)) {
            @mkdir($basePath, 0755, true);
        }

        // 生成唯一文件名:時間戳_隨機字符串.擴展名
        $ext = $this->imageFile->getExtension();
        $fileName = date('YmdHis') . '_' . Yii::$app->security->generateRandomString(8) . '.' . $ext;
        $filePath = $basePath . DIRECTORY_SEPARATOR . $fileName;
        $relativePath = 'uploads/' . $dirName . '/' . $fileName;
        $url = Yii::getAlias('@web') . '/' . $relativePath;

        // 保存文件
        if ($this->imageFile->saveAs($filePath)) {
            // 可選:生成縮略圖、水印、壓縮
            // $this->processImage($filePath);
            
            return [
                'success' => true,
                'message' => '上傳成功',
                'url' => $url,
                'path' => $relativePath,
                'name' => $fileName,
                'size' => $this->imageFile->size,
                'type' => $this->imageFile->type,
            ];
        }

        return ['success' => false, 'message' => '文件保存失敗,請檢查目錄權限'];
    }
}

3. Controller 層:處理上傳請求

<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\UploadForm;

class SiteController extends Controller {
    public function actionUpload() {
        $model = new UploadForm();
        $result = null;

        if (Yii::$app->request->isPost) {
            // 關鍵:獲取上傳文件實例
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
            $model->category = Yii::$app->request->post('category', 'gallery');
            
            $result = $model->upload();
            
            // AJAX 請求返回 JSON
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return $result;
            }
        }

        return $this->render('upload', ['model' => $model, 'result' => $result]);
    }
    
    // 多文件上傳示例
    public function actionMultiUpload() {
        $model = new MultiUploadForm();
        if (Yii::$app->request->isPost) {
            $model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
            $result = $model->uploadAll();
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return $result;
            }
        }
        return $this->render('multi-upload', ['model' => $model]);
    }
}

4. 多文件上傳模型

<?php
namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

class MultiUploadForm extends Model {
    public array $imageFiles = [];
    
    public function rules(): array {
        return [
            [['imageFiles'], 'required'],
            [['imageFiles'], 'each', 'rule' => [
                'file',
                'extensions' => ['jpg', 'png', 'gif'],
                'maxSize' => 2 * 1024 * 1024,
            ]],
        ];
    }
    
    public function uploadAll(): array {
        if (!$this->validate()) {
            return ['success' => false, 'errors' => $this->getErrors()];
        }
        
        $results = [];
        foreach ($this->imageFiles as $file) {
            $result = (new UploadForm())->upload();  // 復用單文件邏輯
            $results[] = $result;
        }
        return ['success' => true, 'files' => $results];
    }
}

5. 安全加固清單

風險防護措施實現位置
惡意腳本上傳MIME 類型白名單 + 擴展名白名單 + 文件頭檢測Model rules()
文件名注入/遍歷隨機重命名,不使用用戶原始文件名Model::upload()
大文件 DoSmaxSize 限制 + Nginx client_max_body_sizeModel + Nginx
圖片處理漏洞 (ImageTragick)ImageMagick 策略限制、優先用 GD服務器配置
直接訪問上傳目錄執行腳本Nginx 禁止 uploads 目錄執行 PHPNginx 配置
CSRFYii 內建 CSRF Token 驗證ActiveForm 自動包含

Nginx 安全配置片段

location /uploads/ {
    # 禁止腳本執行
    location ~ \.(php|php5|phtml|phar)$ {
        deny all;
        return 403;
    }
    # 防止 MIME 嗅探
    add_header X-Content-Type-Options nosniff;
    # 緩存靜態資源
    expires 30d;
    add_header Cache-Control "public";
}

6. 雲存儲擴展 (阿里云 OSS / 騰訊云 COS / AWS S3)

<?php
// components/OssUploader.php
namespace app\components;

use OSS\OssClient;
use yii\base\Component;

class OssUploader extends Component {
    public string $accessKeyId;
    public string $accessKeySecret;
    public string $endpoint;
    public string $bucket;
    
    private OssClient $client;
    
    public function init() {
        parent::init();
        $this->client = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
    }
    
    public function upload(string $localPath, string $objectKey): string {
        $this->client->uploadFile($this->bucket, $objectKey, $localPath);
        return "https://{$this->bucket}.{$this->endpoint}/{$objectKey}";
    }
    
    public function delete(string $objectKey): void {
        $this->client->deleteObject($this->bucket, $objectKey);
    }
}

// Model 中調用
$oss = Yii::$app->ossUploader;
$url = $oss->upload($filePath, "uploads/{$dirName}/{$fileName}");
// 可選:刪除本地臨時文件
@unlink($filePath);

總結

Yii 2 文件上傳最佳實踐核心:**Model 封裝驗證與業務邏輯、Controller 輕量分發、ActiveForm 正確啟用 multipart、隨機文件名防注入、多層安全防護、雲存儲無縫擴展**。遵循此模式可構建安全、可維護、可擴展的上傳系統。

copyright © 萬盛學電腦網 all rights reserved