yii实现图片上传及缩略图生成的方法
本文实例讲述了利用yii框架来实现图片上传功能并在上传成功之后自动生成缩略图的方法,分享给大家供大家参考。具体实现方法如下:
Action文件:
<?php
/**
*TestController.php
*Createdon:2014-1-2612:59:36byOutsider
*/
classTestControllerextendsCController{
/**
*缩略图片生成
*@path图片路径
*@width图片宽度
*@height图片高度
*/
publicfunctionactionGetThumb($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=newEPhpThumb();
$thumb->init();
$thumb->create('.'.$path)
->adaptiveResize($w,$h)
->save('./temp/'.$file_name.'.jpg')
->show();
}
/*
*图片显示
*/
publicfunctionactionList(){
$attache=Attache::model();
$list=$attache->findAll();
$this->render('list',array('list'=>$list));
die;
}
/**
*文件上传
*/
publicfunctionactionIndex(){
$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=newUpload();
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=newAttache();
$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
classUploadextendsCFormModel{
public$file;
publicfunctionrules(){
returnarray(
array('file','file','types'=>'jpg,gif,png,zip'),
);
}
}图片显示页面:
自定义图片大小,缩略图自动生成
<?php
/**
*list.php
*Createdon:2014-1-2613:12:01byOutsider
*/
?>
<?phpforeach($listas$v):?>
<imgsrc="<?phpechoYii::app()->createUrl('test/getThumb',array('path'=>'/uploads'.$v['path'],'w'=>'150','h'=>'150'))?>">
<?phpendforeach;?>
图片上传表单:
<?phpif($uploaded):?>
<p>Filewasuploaded.Check<?phpecho$dir?>.</p>
<?phpendif?>
<?phpechoCHtml::beginForm('','post',array
('enctype'=>'multipart/form-data'))?>
<?phpechoCHtml::error($model,'file')?>
<?phpechoCHtml::activeFileField($model,'file')?>
<?phpechoCHtml::submitButton('Upload')?>
<?phpechoCHtml::endForm()?>
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。