本文實例講述了Yii+upload實現(xiàn)AJAX上傳圖片的方法。分享給大家供大家參考,具體如下:
控制器代碼:
/**
* get ajax uploaded files.
*/
public function actionGetAjax(){
$model=new Attachment();//加載附件模型
$tmpFile = CUploadedFile::getInstanceByName('image');//讀取圖像上傳域,并使用系統(tǒng)上傳組件上傳
$Directroy = Yii::app()->params['uploadPath'];//讀取上傳配置文件,我的配置是/uploads
//創(chuàng)建文件存放路徑
$y = date('Y');
$m = date('m');
$d = date('d');
$Directroy = $Directroy."/";
$pathd = $Directroy.$y."/".$m."/".$d."/";
Tool::makedir(dirname(Yii::app()->BasePath).$pathd); //創(chuàng)建文件夾,此處一定要加上dirname(Yii::app()->BasePath)不然可能會出錯;
if(is_object($tmpFile) && get_class($tmpFile)==='CUploadedFile'){
$filename = time().rand(0,9);
$ext = $tmpFile->extensionName;//上傳文件的擴展名
if($ext=='jpg'||$ext=='gif'||$ext=='png'){
$big = $pathd . $filename . '_600.' . $ext; //310縮略圖
$small = $pathd . $filename . '_310.' . $ext; //310縮略圖
$thumb = $pathd . $filename . '_100.' . $ext; //100縮略圖
$model->zat_thumb = $thumb; //縮略圖
}
$uploadfile = $pathd . $filename . '.' . $ext; //保存的路徑
$model->zat_url = $pathd . $filename . '.' . $ext; //重新賦值
$model->zat_file_name = $filename . '.' . $ext; //文件名稱
$model->zat_title = $tmpFile->name; //文件標題
$model->zat_file_type = $tmpFile->type; //文件類型
$model->zat_file_size = $tmpFile->size; //文件大小
$model->zat_image = 2;
$model->zat_ip = Yii::app()->request->userHostAddress; //上傳IP
//print_r($uploadfile);
}
if($model->save()){
$tmpFile->saveAs(dirname(Yii::app()->BasePath).$uploadfile);//保存到服務器
if($ext=='jpg'||$ext=='gif'||$ext=='png'){
$img = Yii::app()->image->load(dirname(Yii::app()->BasePath).$uploadfile); //使用image-Kohana圖像處理庫擴展
$img->resize(600,600)->quality(85);
$img->save(dirname(Yii::app()->BasePath).$big);//生成600縮略圖
$img->resize(310,310)->quality(85);
$img->save(dirname(Yii::app()->BasePath).$small);//生成310縮略圖
$img->resize(100,100)->quality(85);
$img->save(dirname(Yii::app()->BasePath).$thumb);//生成100縮略圖
}
if($ext=='jpg'||$ext=='gif'||$ext=='png'){
$str = json_encode(
array(
'upfile'=>array(
'zat_id' => Yii::app()->db->getLastInsertID(), //取插ID
'file' => $uploadfile,//原圖
'small' => $small,//310縮略圖
'thumb' => $thumb,//100縮略圖
)
)
);
}else{
$str = json_encode(
array(
'upfile'=>array(
'zat_id' => Yii::app()->db->getLastInsertID(),
'file' => $uploadfile,
)
)
);
}
echo $str;
}
}
VIEW代碼:
<input id="fileupload" type="file" name="image" multiple>
<script src="<?php echo Yii::app()->baseUrl;?>/js/jquery.ui.widget.js"></script>
<script src="<?php echo Yii::app()->baseUrl;?>/js/jquery.iframe-transport.js"></script>
<script src="<?php echo Yii::app()->baseUrl;?>/js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '/Attachment/GetAjax',
success: function (json) {
$('#MemType_zmt_pic').attr('value',json.upfile.file);
$("#images").attr('src',json.upfile.file);
}
});
});
</script>
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。