yii 图片上传

1.下载图片扩展http://www.yiiframework.com/extension/image.下载解压后文件夹里有两个文件夹:helpers和images。将images文件夹放在exetensions里面,然后在protected文件夹里新建helpers文件夹,将解压的helpers的内容放在这个新建的helpers里面。相应的配置如下。

2.相应的配置

 yii 图片上传_第1张图片

3.其中upload.php文件的内容如下:

 

class Upload

{
public static function createImageLink($name, $type, $tmp_name, $width, $height){
$imageMime = array(
'image/gif',
'image/jpeg',
'image/bmp',
'image/png'
//需要时添加...
);
if(!in_array($type, $imageMime)){
return false;
}else{
//获取图片后缀
$temArr = explode('.', $name);
$imageExt = end($temArr);
//时间命名此图片,避免重复
$name = time().uniqid().'.'.$imageExt;
//创建存放路径
$firstThree = Yii::app()->request->baseUrl."images/uploads/".substr(time(),0,3)."/";
$threeSix = Yii::app()->request->baseUrl."images/uploads/".substr(time(),0,3)."/".substr(time(),3,3)."/";
if(!file_exists($firstThree)){
mkdir($firstThree,0777);
if(!file_exists($threeSix)){
mkdir($threeSix,0777);
}
}else{
if(!file_exists($threeSix)){
mkdir($threeSix,0777);
}
}
$path = $threeSix.$name;
//图片处理
$image = Yii::app()->image->load($tmp_name);
$image->resize($width,$height,Image::NONE);
$image->save($path);
//move_uploaded_file($tmp_name,$path);
return $path;
}
}
}

 

控制器内容如下:

 1 public function actionCreate()
 2 {
 3 $model=new Xinxi;
 4 
 5 // Uncomment the following line if AJAX validation is needed
 6 // $this->performAjaxValidation($model);
 7 
 8 if(isset($_POST['Xinxi']))
 9 {
10 $imgUrl='';
11 if($_FILES){
12 $name=$_FILES['Xinxi']['name']['logo'];//上传图片原名
13 $type=$_FILES['Xinxi']['type']['logo'];//上传图片MIME类型
14 $tmp_name=$_FILES['Xinxi']['tmp_name']['logo'];//上传图片临时存放位置
15 $width=100;//缩率图宽
16 $height=100;//缩率图高
17 $imgUrl=Upload::createImageLink($name,$type,$tmp_name,$width,$height);
18 }
19 $model->attributes=$_POST['Xinxi'];
20 $model->logo=$imgUrl;
21 if($model->save())
22 $this->redirect(array('view','id'=>$model->id));
23 }
24 
25 $this->render('create',array(
26 'model'=>$model,
27 ));
28 }
29 
30 public function actionUpdate($id)
31 {
32 $model=$this->loadModel($id);
33 
34 // Uncomment the following line if AJAX validation is needed
35 // $this->performAjaxValidation($model);
36 
37 if(isset($_POST['Xinxi']))
38 { $imgUrl=$model->logo;
39 if($_FILES && $_FILES['Xinxi']['name']['logo']!=''){
40 $name=$_FILES['Xinxi']['name']['logo'];//上传图片原名
41 $type=$_FILES['Xinxi']['type']['logo'];//上传图片MIME类型
42 $tmp_name=$_FILES['Xinxi']['tmp_name']['logo'];//上传图片临时存放位置
43 $width=100;//缩率图宽
44 $height=100;//缩率图高
45 $imgUrl=Upload::createImageLink($name,$type,$tmp_name,$width,$height);
46 }
47 $model->attributes=$_POST['Xinxi'];
48 $model->logo=$imgUrl;
49 if($model->save())
50 $this->redirect(array('view','id'=>$model->id));
51 }
52 
53 $this->render('update',array(
54 'model'=>$model,
55 ));
56 }

 

view内容:

yii 图片上传_第2张图片

 

这样就可以实现图片上传了。

你可能感兴趣的:(图片上传)