本文實例講述了利用yii框架來實現圖片上傳功能並在上傳成功之後自動生成縮略圖的方法,分享給大家供大家參考。具體實現方法如下:
Action文件:
復制代碼 代碼如下:<?php
/**
* TestController.php
* Created on: 2014-1-26 12:59:36 by Outsider
*/
class TestController extends CController {
/**
* 縮略圖片生成
* @ path 圖片路徑
* @ width 圖片寬度
* @ height 圖片高度
*/
public function actionGetThumb($path, $w, $h) {
$file_name = md5($path . $w . $h);
if (file_exists('./temp/' . $file_name . '.jpg')) {
header('location:/temp/' . $file_name . '.jpg');
Yii::app()->end();
}
Yii::import("ext.EPhpThumb.EPhpThumb");
$thumb = new EPhpThumb();
$thumb->init();
$thumb->create('.' . $path)
->adaptiveResize($w, $h)
->save('./temp/' . $file_name . '.jpg')
->show();
}
/*
* 圖片顯示
*/
public function actionList() {
$attache = Attache::model();
$list = $attache->findAll();
$this->render('list', array('list' => $list));
die;
}
/**
* 文件上傳
*/
public function actionIndex() {
$path = getcwd() . 'uploads';
$dir = DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m');
$dir = str_replace("\", "/", $dir);
$uploads_dir = str_replace("\", "/", $path . $dir);
if (!is_dir($uploads_dir) || !is_writeable($uploads_dir)) {
mkdir($uploads_dir, 0777, TRUE);
touch($uploads_dir . '/index.html');
}
$uploaded = false;
$model = new Upload();
if (isset($_POST['Upload'])) {
$model->attributes = $_POST['Upload'];
$file = CUploadedFile::getInstance($model, 'file');
$newName = substr(md5($file->extensionName . round((microtime(true) * 1000))), 0, 17) . '.' . $file->extensionName;
$file_name = $uploads_dir . '/' . $newName;
if ($model->validate()) {
$attache = new Attache();
$uploaded = $file->saveAs($file_name, TRUE);
$attache->name = $file->getName();
$attache->path = $dir . '/' . $newName;
$attache->create_time = time();
$attache->save();
}
}
$this->render('index', array(
'model' => $model,
'uploaded' => $uploaded,
'dir' => $uploads_dir,
));
}
}
Upload.php:
復制代碼 代碼如下:<?php
class Upload extends CFormModel {
public $file;
public function rules() {
return array(
array('file', 'file', 'types' => 'jpg, gif, png,zip'),
);
}
}
圖片顯示頁面:
自定義圖片大小,縮略圖自動生成
復制代碼 代碼如下:<?php
/**
* list.php
* Created on: 2014-1-26 13:12:01 by Outsider
*/
?>
<?php foreach ($list as $v): ?>
<img src="<?php echo Yii::app()->createUrl('test/getThumb', array('path' => '/uploads' . $v['path'], 'w' => '150', 'h' => '150')) ?>">
<?php endforeach; ?>
圖片上傳表單:
復制代碼 代碼如下:<?php if($uploaded):?>
<p>File was uploaded. Check <?php echo $dir?>.</p>
<?php endif ?>
<?php echo CHtml::beginForm('','post',array
('enctype'=>'multipart/form-data'))?>
<?php echo CHtml::error($model, 'file')?>
<?php echo CHtml::activeFileField($model, 'file')?>
<?php echo CHtml::submitButton('Upload')?>
<?php echo CHtml::endForm()?>
希望本文所述對大家基於Yii框架的PHP程序設計有所幫助。