关于YII框架结合swfupload的问题 [ 未指定版本 ]
关于YII框架结合swfupload的问题:
controller中代码:
public function actionUpload()
{
if (isset($_POST["PHPSESSID"])) {
session_id($_POST["PHPSESSID"]);
}
//session_start();
ini_set("html_errors", "0");
if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
echo "错误:无效的上传!";
exit(0);
}
// Get the image and create a thumbnail
$file_types=explode(".",$_FILES["Filedata"]["name"]);
$file_type=$file_types[count($file_types)-1];
if(strtolower($file_type)=='gif' )
{
$img = imagecreatefromgif($_FILES["Filedata"]["tmp_name"]);
}
else if(strtolower($file_type)=='png')
{
$img = imagecreatefrompng($_FILES["Filedata"]["tmp_name"]);
}
else if(strtolower($file_type)=='bmp')
{
$img = imagecreatefromwbmp($_FILES["Filedata"]["tmp_name"]);
}
else
{
$img = imagecreatefromjpeg($_FILES["Filedata"]["tmp_name"]);
}
if (!$img) {
echo "错误:无法创建图像 ". $_FILES["Filedata"]["tmp_name"];
exit(0);
}
$width = imageSX($img);
$height = imageSY($img);
if (!$width || !$height) {
echo "错误:无效的高或高";
exit(0);
}
// Build the thumbnail
$target_width = 100;
$target_height = 100;
$target_ratio = $target_width / $target_height;
$img_ratio = $width / $height;
if ($target_ratio > $img_ratio) {
$new_height = $target_height;
$new_width = $img_ratio * $target_height;
} else {
$new_height = $target_width / $img_ratio;
$new_width = $target_width;
}
if ($new_height > $target_height) {
$new_height = $target_height;
}
if ($new_width > $target_width) {
$new_height = $target_width;
}
$new_img = ImageCreateTrueColor(100, 100);
if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, 0)) { // Fill the image black
echo "错误:不能填充新图片";
exit(0);
}
if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0, 0, $new_width, $new_height, $width, $height)) {
echo "错误:不能调整大小的图像";
exit(0);
}
if (!isset($_SESSION["file_info"])) {
$_SESSION["file_info"] = array();
}
ob_start();
imagejpeg($new_img);
$imagevariable = ob_get_contents();
ob_end_clean();
$file_id = md5($_FILES["Filedata"]["tmp_name"] + rand()*100000);
$_SESSION["file_info"][$file_id] = $imagevariable;
echo "FILEID:" . $file_id; // Return the file id to the script
include("upimg.class.php");
include("waterimg.class.php");
if(!empty($_FILES["Filedata"]))
{
$folder= Yii::app()->basePath . '/../images/'.date("Y-m-d");
$up = new upimg("$folder","$folder"); //可以写成:$up = new upimg();
$up->autoThumb = TRUE; //可省略
$up->srcDel=TRUE;
$up->thumbWidth = 550; //可省略
$up->thumbHeight = 400; //可省略
$up->maxsize=2014; //上传文件大小单位是kb
/*$op=array(
'uploadFolder'=>'upload/images/'.date('Y-m-d'),
'thumbFolder'=>'upload/thumbs/'.date('Y-m-d'),
'srcDel'=>false,
'autoThumb'=>true,
'thumbWidth'=>550,
'thumbHeight'=>400,
'maxSize'=>2014,
);
$up = new upimg($op);*/
$result= $up->upload('Filedata'); // HTML中<input />的name属性值
$water="logo.png";
$waterimage= new waterimage($up->thumbPath,$water,3);//添加水印
$waterimage->waterimg();
$_SESSION["upload_tem"]=$_SESSION["upload_tem"].",".$up->thumbPath;
$_SESSION["upload_tem"]=trim($_SESSION["upload_tem"],",");
}
}
view中的代码:
<script type="text/javascript" src="<?php echo Yii::app()->baseUrl; ?>/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->baseUrl; ?>/js/swfupload.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->baseUrl; ?>/js/handlers.js"></script>
<?php
session_start();
$_SESSION["file_info"] = array();
unset($_SESSION["upload_tem"]);
$uurl = $this->createUrl('site/Upload',array('type'=>'1'));
//echo $uurl;
//echo CHtml::normalizeUrl($uurl);
?>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
upload_url: '<?php echo $uurl; ?>',
post_params: {"PHPSESSID": "<?php echo session_id();?>"},
file_size_limit : "2 MB",
file_types : "*.jpg;*.png;*.gif;*.bmp",
file_types_description : "JPG Images",
file_upload_limit : "100",
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
button_image_url : "<?php echo Yii::app()->baseUrl; ?>/css/upload.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 113,
button_height: 33,
button_text : '',
button_text_style : '.spanButtonPlaceholder { font-family: Helvetica, Arial, sans-serif; font-size: 14pt;} ',
button_text_top_padding: 0,
button_text_left_padding: 0,
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND,
flash_url : "<?php echo Yii::app()->baseUrl; ?>/js/swfupload.swf",
custom_settings : {
upload_target : "divFileProgressContainer"
},
debug: false
});
};
</script>
<div style="width:610px; height:auto; border:1px solid #e1e1e1; font-size:12px; padding:10px;">
<span id="spanButtonPlaceholder"></span>
<div id="divFileProgressContainer" ></div>
<div id="thumbnails">
<ul id="pic_list" style="margin:5px;"></ul>
<div style="clear: both;"></div>
</div>
</div>
两个类
upimg.class.php:
<?php
class upimg{
public $uploadFolder = 'upload'; // 图片存放目录
public $thumbFolder = 'upload/thumb'; // 缩略图存放目录
public $thumbWidth = ''; // 缩略图宽度
public $thumbHeight = ''; // 缩略图高度
public $autoThumb = ''; // 是否自动生成缩略图
public $error = ''; // 错误信息
public $imgPath = ''; // 上传成功后的图片位置
public $thumbPath = ''; // 上传成功后的缩略图位置
public $maxsize='';
// 说明:初始化,创建存放目录
function __construct($uploadFolder = 'upload', $thumbFolder = 'upload/thumb'){
$this->uploadFolder = $uploadFolder;
$this->thumbFolder = $thumbFolder;
$this->
_mkdir();
}
/*
function __construct($options=array()){
if(!empty($options)){
$options_values = array_values($options);
foreach(array_keys($options) as $index => $key){
$this->$key = $options_values[$index];
}
}
$this->_mkdir();
}*/
// 说明:上传图片,参数是<input />的name属性值;成功返回图片的相对URL,失败返回FALSE和错误信息(在$this->error里)
// bool/sting upload(string $html_tags_input_attrib_name);
function upload($inputName){ // 上传操作,参数是input标签的name属性。
if ($this->error){ // 如果有错,直接返回(例如_mkdir)
return FALSE;
}
if(!$_FILES[$inputName]["name"]){
$this->error = '没有上传图片';
return FALSE;
}
//检测文件大小
if($_FILES[$inputName]["size"] > ($this->maxsize*1024)){
$this->error = '上传文件'.$inputName.'太大,最大支持'.ceil($this->maxsize/1024).'kb的文件';
return FALSE;
}
if($_FILES[$inputName]["name"]){
$isUpFile = $_FILES[$inputName]['tmp_name'];
if (is_uploaded_file($isUpFile)){
$imgInfo = $this->_getinfo($isUpFile);
if (FALSE == $imgInfo){
return FALSE;
}
$extName = $imgInfo['type'];
$microSenond = floor(microtime()*10000);// 取一个毫秒级数字,4位。
$newFileName = $uploadFolder . '/' . date('YmdHis') . $microSenond . '.' . $extName ; // 所上传图片的新名字。
$location = $this->uploadFolder . $newFileName;
$result = move_uploaded_file($isUpFile, $location);
if ($result)
{
if (TRUE == $this->autoThumb)
{ // 是否生成缩略图
$thumb = $this->thumb($location, $this->thumbWidth, $this->thumbHeight);
if (FALSE == $thumb)
{
return FALSE;
}
}
//是否删除原图
if(TRUE==$this->srcDel)
{
@unlink($location);
}
$this->imgPath = $location;
return $location;
}else{
$this->error = '移动临时文件时出错';
return FALSE;
}
}else{
$uploadError = $_FILES[$inputName]['error'];
if (1 == $uploadError){ // 文件大小超过了php.ini中的upload_max_filesize
$this->error = '文件太大,服务器拒绝接收大于' . ini_get('upload_max_filesize') . '的文件';
return FALSE;
}elseif (3 == $uploadError){ // 上传了部分文件
$this->error = '上传中断,请重试';
return FALSE;
}elseif (4 == $uploadError){
$this->error = '没有文件被上传';
return FALSE;
}elseif (6 == $uploadError){
$this->error = '找不到临时文件夹,请联系您的服务器管理员';
return FALSE;
}elseif (7 == $uploadError){
$this->error = '文件写入失败,请联系您的服务器管理员';
return FALSE;
}else{
if (0 != $uploadError){
$this->error = '未知上传错误,请联系您的服务器管理员';
return FALSE;
}
} // end if $uploadError
} // end if is_uploaded_file else
} // end if $_FILES[$inputName]["name"]
}
// 说明:获取图片信息,参数是上传后的临时文件,成功返回数组,失败返回FALSE和错误信息
// array/bool _getinfo(string $upload_tmp_file)
private function _getinfo($img){
if (!file_exists($img)){
$this->error = '找不到图片,无法获取其信息';
return FALSE;
}
$tempFile = @fopen($img, "rb");
$bin = @fread($tempFile, 2); //只读2字节
@fclose($tempFile);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
$fileType = '';
switch ($typeCode){ // 6677:bmp 255216:jpg 7173:gif 13780:png 7790:exe 8297:rar 8075:zip tar:109121 7z:55122 gz 31139
case '255216':
$fileType = 'jpg';
break;
case '6677':
$fileType = 'bmp';
break;
case '7173':
$fileType = 'gif';
break;
case '13780':
$fileType = 'png';
break;
default:
$fileType = 'unknown';
}
if ($fileType == 'jpg' || $fileType == 'gif' || $fileType == 'png' || $fileType == 'bmp'){
$imageInfo = getimagesize($img);
$imgInfo['size'] = $imageInfo['bits'];
$imgInfo["type"] = $fileType;
$imgInfo["width"] = $imageInfo[0];
$imgInfo["height"] = $imageInfo[1];
return $imgInfo;
}else{ // 非图片类文件信息
$this->error = '图片类型错误';
return FALSE;
}
} // end _getinfo
// 说明:生成缩略图,等比例缩放或拉伸
// bool/string thumb(string $uploaded_file, int $thumbWidth, int $thumbHeight, string $thumbTail);
function thumb($img, $thumbWidth = 300, $thumbHeight = 200,$thumbTail = '_thumb')
{
$filename = $img; // 保留一个名字供新的缩略图名字使用
$imgInfo = $this->_getinfo($img,$i);
if(FALSE == $imgInfo)
{
return FALSE;
}
$imgType = $imgInfo['type'];
switch ($imgType)
{ // 创建一个图,并给出扩展名
case "jpg" :
$img = imagecreatefromjpeg($img);
$extName = 'jpg';
break;
case 'gif' :
$img = imagecreatefromgif($img);
$extName = 'gif';
break;
case 'bmp' :
$img = imagecreatefromgif($img);
$extName = 'bmp';
break;
case 'png' :
$img = imagecreatefrompng($img);
$extName = 'png';
break;
default : // 如果类型错误,生成一张空白图
$img = imagecreate($thumbWidth,$thumbHeight);
imagecolorallocate($img,0x00,0x00,0x00);
$extName = 'jpg';
}
// 缩放后的图片尺寸(小则拉伸,大就缩放)
$imgWidth = $imgInfo['width'];
$imgHeight = $imgInfo['height'];
if($imgHeight > $imgWidth)
{ // 竖图
$newHeight = $thumbHeight;
$newWidth = ceil($imgWidth / ($imgHeight / $thumbHeight ));
}
else if($imgHeight < $imgWidth)
{ // 横图
$newHeight = ceil($imgHeight / ($imgWidth / $thumbWidth ));
$newWidth = $thumbWidth;
}
else if($imgHeight == $imgWidth)
{ // 等比例图
$newHeight = $thumbWidth;
$newWidth = $thumbWidth;
}
$bgimg = imagecreatetruecolor($newWidth,$newHeight);
$bg = imagecolorallocate($bgimg,0x00,0x00,0x00);
imagefill($bgimg,0,0,$bg);
$sampled = imagecopyresampled($bgimg,$img,0,0,0,0,$newWidth,$newHeight,$imgWidth,$imgHeight);
if(!$sampled )
{
$this->error = '缩略图生成失败';
$this->path=$this->uploadFolder . '/' . $filename;
return FALSE;
}
$filename = basename($filename);
$newFileName = substr($filename, 0, strrpos($filename, ".")) . $thumbTail . '.' . $extName ; // 新名字
$thumbPath = $this->thumbFolder . '/' . $newFileName;
switch ($extName){
case 'jpg':
$result = imagejpeg($bgimg, $thumbPath);
break;
case 'gif':
$result = imagegif($bgimg, $thumbPath);
break;
case 'png':
$result = imagepng($bgimg, $thumbPath);
break;
default: // 上边判断类型出错时会创建一张空白图,并给出扩展名为jpg
$result = imagejpeg($bgimg, $thumbPath);
}
if ($result)
{
$this->thumbPath = $thumbPath;
$this->path=$this->uploadFolder . '/' . $filename;
return $thumbPath;
}
else
{
$this->error = '缩略图创建失败';
$this->path=$this->uploadFolder . '/' . $filename;
return FALSE;
}
} // end thumb
// 说明:创建图片的存放目录
private function _mkdir()
{ // 创建图片上传目录和缩略图目录
if(!is_dir($this->uploadFolder))
{
$dir = explode('/', $this->uploadFolder);
foreach($dir as $v)
{
if($v)
{
$d .= $v . '/';
if(!is_dir($d))
{
$state = mkdir($d);
if(!$state)
{
$this->error = '在创建目录' . $d . '时出错!';
}
}
}
}
}
if(!is_dir($this->thumbFolder) && TRUE == $this->autoThumb)
{
$dir = explode('/', $this->thumbFolder);
foreach($dir as $v)
{
if($v)
{
$d .= $v . '/';
if(!is_dir($d))
{
$state = mkdir($d);
if(!$state)
{
$this->error = '在创建目录' . $d . '时出错!';
}
}
}
}
}
}
}
?>
waterimg.class.php:
<?php
class waterimage{
//-----www.oophper.com原创
//要加水印的图片,水印图片,文字水印,水印位置 :0:左上 1:右上 2:左下 3:右下 4:底部居中
public $img,$waterimg,$waterword,$waterpos;
function __construct($img,$waterimg,$waterpos){
$this->img = $img;
$this->waterimg = $waterimg;
//$this->waterword = $waterword;
$this->waterpos = $waterpos;
}
//***********加水印 主方法***************//
//-----www.oophper.com原创
function waterimg(){
if(!file_exists("$this->img")){
echo '文件未找到';exit;
}
//获取预处理图片信息
$imginfo = getimagesize("$this->img");
$img_w = $imginfo[0];
$img_h = $imginfo[1];
$img_type = $imginfo[2];
//获取水印图片信息
$waterimginfo = getimagesize("$this->waterimg");
$wimg_w = $waterimginfo[0];
$wimg_h = $waterimginfo[1];
$wimg_type = $waterimginfo[2];
//创建预处理图像
$bgimg = $this->createimg($img_type);
//创建水印图像
$wimg = $this->createwater($wimg_type);
//获取水印位置
$pos = $this->getpos($this->waterpos,$img_w ,$img_h ,$wimg_w ,$wimg_h);
$pos_x = $pos[0];
$pos_y = $pos[1];
//echo $this->waterpos.'---'.$pos_x.'---'.$pos_y;exit;
//添加水印
imagecopy($bgimg, $wimg, $pos_x, $pos_y, 0, 0, $wimg_w, $wimg_h);
imagedestroy($wimg);//从内存中销毁
//输出处理后的文件
$this->output($bgimg,$img_type);
imagedestroy($bgimg);//从内存中销毁
}
//***********根据选项计算水印位置************//
//参数:目标位置:0,1,2,3,4
//参数:目标文件宽度高度,水印文件宽度高度
//注释:为避免太过边角化,位置都稍加偏移
////-----www.oophper.com原创
//****************************************//
function getpos($waterpos,$img_w ,$img_h ,$wimg_w ,$wimg_h){
if($img_w<$wimg_w || $img_h<$wimg_h){echo '源文件小于水印图片,不添加水印';exit;}
switch($waterpos){
case '0'://左上
$pos[0] = 10;
$pos[1] = 6;break;
case '1'://右上
$pos[0] = $img_w - $wimg_w - 10;
$pos[1] = 0;break;
case '2'://左下
$pos[0] = 0;
$pos[1] = $img_h - $wimg_h - 6;
break;
case '3'://右下
$pos[0] = $img_w - $wimg_w - 10;
$pos[1] = $img_h - $wimg_h - 2;break;
case '4'://底部居中
$pos[0] = ($img_w - $wimg_w)/2;
$pos[1] = $img_h - $wimg_h - 6;break;
}
return $pos;
}
//***********根据不同预处理图片格式创建新图像************//
//参数:目标文件类型
////-----www.oophper.com原创
//****************************************//
function createimg($img_type){
switch($img_type){
case 1:
$bgimg = imagecreatefromgif($this->img);break;//gif
case 2:
$bgimg = imagecreatefromjpeg($this->img);break;//jpg
case 3:
$bgimg = imagecreatefrompng($this->img);break;//png
case 6:
$bgimg = imagecreatefromwbmp($this->img);break;//bmp
default:
echo $img_type.'不支持的文件类型';exit;
}
return $bgimg;
}
//***********根据不同水印图片格式创建新图像************//
//参数:目标文件类型
////-----www.oophper.com原创
//****************************************//
function createwater($wimg_type){
switch($wimg_type){
case 1:
$wimg = imagecreatefromgif($this->waterimg);break;//gif
case 2:
$wimg = imagecreatefromjpeg($this->waterimg);break;//jpg
case 3:
$wimg = imagecreatefrompng($this->waterimg);break;//png
case 6:
$wimg = imagecreatefromwbmp($this->waterimg);break;//bmp
default:
echo $wimg_type.'不支持的文件类型';exit;
}
return $wimg;
}
//***********根据原始图片格式输出不同文件************//
//参数:目标文件类型
//参数:合成后的文件资源
//-----www.oophper.com原创
//****************************************//
function output($imgsource,$img_type){
switch($img_type){
case 1:
imagegif($imgsource,$this->img);break;//gif
case 2:
imagejpeg($imgsource,$this->img);break;//jpg
case 3:
imagepng($imgsource,$this->img);break;//png
case 6:
imagewbmp($imgsource,$this->img);break;//bmp
default:
echo '不支持的文件类型';exit;
}
}
function __destruct(){
}
}
现在的问题是,我点击按钮上传图片之后,提示‘XXX.jpg,图片上传成功’ 图片确实存进了文件夹里,不过下方展示的图片(缩略图)是红叉,也就是没有显示。请问哪里有问题,望指教。
共 1 个回答
leo007ok
最后登录:2015-01-16
在线时长:11小时12分
- 粉丝1
- 金钱0
- 威望0
- 积分110