Yii Framework 內建強大的檔案上傳支援,結合擴充元件可快速實現圖片上傳、驗證、儲存與縮圖生成。本文以完整 MVC 程式碼示範標準流程,並整合 ThinkPHP 風格的縮圖類庫。
<?php
class Upload extends CActiveRecord {
public $image; // 非資料庫欄位,用於接收上傳檔案
public static function model($className = __CLASS__) {
return parent::model($className);
}
public function tableName() {
return '{{resource}}'; // 資料表名,前綴在 main.php 設定
}
public function rules() {
return array(
array('image', 'file', 'types' => 'jpg, gif, png', 'maxSize' => 1024*1024*2, 'tooLarge' => '檔案不得超過 2MB'),
);
}
}
<?php
class UploadController extends Controller {
public function actionIndex() {
$model = new Upload;
if (isset($_POST['Upload'])) {
$model->image = CUploadedFile::getInstance($model, 'image');
if ($model->validate()) {
$ext = $model->image->getExtensionName();
$fileName = uniqid() . '.' . $ext;
$savePath = 'assets/' . $fileName;
$model->image->saveAs($savePath);
// 生成縮圖 (需先引入 Image 擴充類)
Yii::import('application.extensions.Image');
Image::thumb($savePath, 'assets/thumb_' . $fileName, '', 200, 150);
// 這裡可將 $fileName 寫入 resource 表
}
}
$this->render('index', array('model' => $model));
}
}
<?php
echo CHtml::form('', 'post', array('enctype' => 'multipart/form-data'));
echo CHtml::activeFileField($model, 'image');
echo CHtml::error($model, 'image');
echo CHtml::submitButton('上傳');
echo CHtml::endForm();
?>
整合 ThinkPHP 縮圖邏輯,支援 GD2、透明度保留、隔行掃描。
<?php
class Image extends CController {
public static function getImageInfo($img) {
$info = getimagesize($img);
if ($info !== false) {
return array(
'width' => $info[0],
'height' => $info[1],
'type' => strtolower(substr(image_type_to_extension($info[2]), 1)),
'size' => filesize($img),
'mime' => $info['mime']
);
}
return false;
}
public static function thumb($image, $thumbname, $type = '', $maxWidth = 200, $maxHeight = 50, $interlace = true) {
$srcInfo = self::getImageInfo($image);
if (!$srcInfo) return false;
$srcW = $srcInfo['width']; $srcH = $srcInfo['height'];
$type = $type ?: $srcInfo['type'];
$scale = min($maxWidth/$srcW, $maxHeight/$srcH);
if ($scale >= 1) { $w = $srcW; $h = $srcH; }
else { $w = (int)($srcW*$scale); $h = (int)($srcH*$scale); }
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
if (!function_exists($createFun)) return false;
$srcImg = $createFun($image);
$thumbImg = ($type != 'gif' && function_exists('imagecreatetruecolor'))
? imagecreatetruecolor($w, $h)
: imagecreate($w, $h);
// PNG/GIF 透明度處理
if ($type == 'png') {
imagealphablending($thumbImg, false);
imagesavealpha($thumbImg, true);
} elseif ($type == 'gif') {
$trnprt = imagecolortransparent($srcImg);
if ($trnprt >= 0) {
$trnprtColor = imagecolorsforindex($srcImg, $trnprt);
$trnprt = imagecolorallocate($thumbImg, $trnprtColor['red'], $trnprtColor['green'], $trnprtColor['blue']);
imagefill($thumbImg, 0, 0, $trnprt);
imagecolortransparent($thumbImg, $trnprt);
}
}
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $w, $h, $srcW, $srcH);
if ($type == 'jpg' || $type == 'jpeg') imageinterlace($thumbImg, $interlace);
$imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
$imageFun($thumbImg, $thumbname);
imagedestroy($thumbImg); imagedestroy($srcImg);
return $thumbname;
}
}
// protected/config/main.php
'import' => array(
'application.models.*',
'application.components.*',
'application.extensions.*', // 新增此行
),
CUploadedFile::getInstance 取得上傳物件,配合 file 驗證器限制類型/大小。saveAs() 參數必須為完整檔案路徑,非目錄。assets/ 需給 Web 伺服器寫入權限 (Linux: chmod 777 assets)。此架構清晰分離驗證、儲存、後處理,易於擴充水印、格式轉換、雲端儲存等功能。