作者:心如止水向北飞2012_737 | 来源:互联网 | 2014-05-16 09:11
网站开发中,批量上传图片功能在所难免,如果你想自己写一个出来,那么折腾又何必重复造轮呢。Yii官网有swfupload extension,但我测试下来并没那么的好用,所以我参考了swfupload demo?例子,结合yii,自己实现了个extension,并修改了swfupload中相关js,可以在批量上传图片中给每个图片添加alt属性,那么废话不多说,我们直接来看例子:
笔者是写一个extension,当然您也可以写成widget:
目录结构:
/extenstion
views
view.php
CSwfupload.php
view.php中内容如下,笔者为保持swfupload demo原味,基本参照原代码:
request->baseUrl;?>/css/swfupload.css" rel="stylesheet" type="text/css" />
CSwfupload.php文件内容如下 :
render("view", array());
}
public function run()
{
$baseUrl = Yii::app()->request->baseUrl;
Yii::app()->clientScript->registerScriptFile($baseUrl . '/js/swfupload/swfupload.js', CClientScript::POS_HEAD);
Yii::app()->clientScript->registerScriptFile($baseUrl . '/js/swfupload/swfupload.queue.js', CClientScript::POS_HEAD);
Yii::app()->clientScript->registerScriptFile($baseUrl . '/js/swfupload/fileprogress.js', CClientScript::POS_HEAD);
Yii::app()->clientScript->registerScriptFile($baseUrl . '/js/swfupload/handlers.js', CClientScript::POS_HEAD);
}
}
ok,extension我们已经写好,下面看看,在后台如何调用并上传图片
在后台调用:
beginWidget('CActiveForm', array(
'id'=>'jos-cos-hotelpic-form',
'enableAjaxValidation'=>false,
)); ?>
widget('application.extensions.swfupload.CFSwfUpload', array(
'config' => array(
'upload_url' => Yii::app()->createUrl('action/upload'),
'post_params' => array('PHPSESSID'=>$_COOKIE['PHPSESSID']), //必须传sessionid,flash提交无法传递头信息
'file_size_limit' => '2 MB',
)
)
);
?>
endWidget(); ?>
生成的界面如下:
controller中上传图片处理程序:
public function actionUpload()
{
if (isset($_FILES["Filedata"])) {
$upload_file = $_FILES['Filedata'];
$file_info = pathinfo($upload_file['name']);
$file_type = $file_info['extension'];
$filename = uniqid().'.'.$file_info['extension'];
$saveFile = 'upload/'.$filename;
$name = $_FILES['Filedata']['tmp_name'];
if (move_uploaded_file($name, $saveFile)) {
echo '上传成功';
}else{
}
}
Yii::app()->end();
}
需要注意的时,swfupload默认上传图片没有添加图片描述的功能,需要改fileprogress.js,添加如下代码于44行(progressStatus.innerHTML = " ";)之后:
var imageAlt = document.createElement("div");
imageAlt.className = "imageAlt";
imageAlt.innerHTML = "";
this.fileProgressElement.appendChild(imageAlt);
一切OK。