Yii 2 內建 yii\web\UploadedFile 類封裝了文件上傳的完整流程。本文提供從 View 表單構建、Controller 處理、驗證規則、安全防護、多文件上傳到雲存儲擴展的完整最佳實踐指南。
<?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']),
]); ?>
= $form->field($model, 'imageFile')->fileInput(['accept' => 'image/*']) ?>
= $form->field($model, 'category')->dropDownList([
'avatar' => '頭像',
'document' => '文檔',
'gallery' =>相冊',
]) ?>
= Html::submitButton('上傳', ['class' => 'btn btn-primary', 'name' => 'upload-button']) ?>
= $result['message'] ?>
<?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' => '文件保存失敗,請檢查目錄權限'];
}
}
<?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]);
}
}
<?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];
}
}
| 風險 | 防護措施 | 實現位置 |
|---|---|---|
| 惡意腳本上傳 | MIME 類型白名單 + 擴展名白名單 + 文件頭檢測 | Model rules() |
| 文件名注入/遍歷 | 隨機重命名,不使用用戶原始文件名 | Model::upload() |
| 大文件 DoS | maxSize 限制 + Nginx client_max_body_size | Model + Nginx |
| 圖片處理漏洞 (ImageTragick) | ImageMagick 策略限制、優先用 GD | 服務器配置 |
| 直接訪問上傳目錄執行腳本 | Nginx 禁止 uploads 目錄執行 PHP | Nginx 配置 |
| CSRF | Yii 內建 CSRF Token 驗證 | ActiveForm 自動包含 |
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";
}
<?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、隨機文件名防注入、多層安全防護、雲存儲無縫擴展**。遵循此模式可構建安全、可維護、可擴展的上傳系統。