bootstrap 上传 没搞懂

之前离职的同事写的,摘下来了,但是有些东西没搞懂

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <title>Bootstrap 101 Template</title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <!-- Bootstrap -->
      <link href="css/bootstrap.min.css" rel="stylesheet">

      <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
      <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
      <!--[if lt IE 9]>
         <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
         <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
      <![endif]-->
   </head>
   <body>
      
      <div class="form-inline">
         <input name="News[picture_url]" type="text" id="license_url" value="" readonly οnclick="open_upload('license_url',6)" class="form-control" />
         <button type="button" οnclick="open_upload('license_url',6)" class="btn btn-sm btn-info">上传</button>
      </div>

      <!-- uploadfile modal -->
      <div class="modal fade" id="fileModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
         <div class="modal-dialog">
            <div class="modal-content">
               <div class="modal-header">
                  <h4 class="modal-title">上传的图片</h4>
               </div>
               <div class="modal-body">
                  <form action="/upload/index" method="post" role="form" target="up_frame" οnsubmit="return chk();" enctype="multipart/form-data">
                     <div class="form-group form-inline">
                        <label for="exampleInputFile">选择上传的文件 </label>
                        <input type="hidden" value="" name="filetype" id="filetype" />
                        <input type="hidden" value="" name="control" id="control" />
                        <input type="file" id="files" name="fileup" class="form-control input-sm" id="exampleInputFile" accept="image/gif, image/jpeg, image/x-png" />
                        <p class="help-block">请选择图文件,文件大小要求小于1024Kb</p>
                        <p align="center">
                           <button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-open" title="open"></i>上传文件</button>   
                           <button type="button" class="btn btn-danger" οnclick="close_upload()"><i class="glyphicon glyphicon-ban-circle" title="ban-circle"></i>关闭上传</button>
                        </p>
                     </div>
                     <iframe src="" name="up_frame" id="up_frame" style="display:none" frameborder="0"></iframe>
                  </form>
               </div>
            </div>
         </div>
      </div>

      <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
      <script src="https://code.jquery.com/jquery.js"></script>
      <!-- Include all compiled plugins (below), or include individual files as needed -->
      <script src="js/bootstrap.min.js"></script>
      <script type="text/javascript">
         function chk(){
            if (document.getElementById("files").value === "") {
               alert("上传文件不能为空");
               document.getElementById("files").focus();
               return false;
            };
         }

         function open_upload(e,s){
            $("#fileModal").modal("show");
            $("#files").val($("#"+e).val());
            $("#control").val(e);
            $("#filetype").val(s);
         }

         function close_upload(){
            $("#fileModal").modal("hide");
         }

         function upload_success(info, e, s, w_str){
            if (info=="ok") {
               $("#fileModal").modal("hide");
               var conl = document.getElementById(s);
               conl.value=e;
               $("#login-form").append(w_str);

                /*
               var objs=$.parseJSON(j_str);
               $("#width").val(objs.image_width);
               $("#height").val(objs.image_height);
               */


            }else{
               $("#fileModal").modal("hide");
               $("#x_alert").html(e);
               $("#x_alert").show();
               window.setTimeout(function(){
                  $("#x_alert").hide();
               },3000)
            }
         }


      </script>
   </body>
</html>

UploadController.php

<?php

/*
 * 此组件用来上传文件
 */

/**
 * Description of UploadController
 *
 * @author cityxiao
 */
class UploadController extends Controller{
    //put your code here
    
  //private $uppath="/zh_o2o/main/upload";
 
   // private $uppath="/upload";

	/**
     * @return array action filters
     */
    public function filters()
    {
            return array(
                    'accessControl', // perform access control for CRUD operations
                    'postOnly + delete', // we only allow deletion via POST request
            );
    }
    
    public function actionIndex(){
		//echo "<script>parent.upload_success('ok','hhhh','','')</script>";
        var_dump($_REQUEST);

		$up_dir=$this->uplad_dir();
        if($_REQUEST['control'] == 'license_url'){


        }
		$upfile=  CUploadedFile::getInstanceByName("fileup");
		$obj = $_POST["control"];
		$typ = $_POST["filetype"];

		$arr=json_decode(Yii::app()->params['imgthumb'],true);


		if(!is_null($upfile)){
           	$up_rule='gif,jpg,png,bmp,jpeg';

            $oldname = $upfile->getname();

            $news_name1=date("YmdHis").time();
			$news_name=$news_name1.".".$upfile->extensionName;
			$imagetype = strtolower($upfile->extensionName);
			//$filesize=$upfile->getSize();
            if($obj == 'license_url'){
                $basepath = str_replace("\\","/",Yii::app()->basepath);
                $basepath = trim($basepath,"/protected");
                echo $basepath;
                echo "99999";
                if($upfile->saveAs($up_dir.$news_name)){
                    $savepath = str_replace($basepath,"",$up_dir.$news_name);
                    echo "<script>parent.upload_success('ok','".$oldname."','".$obj."','<input type=\"test\" name=\"license_url\" value=\"{$savepath}\" hidden>')</script>";
                    exit;
                }else{
                    echo "fail!1";
                    exit;
                }

            }
			if(preg_match('/'.$upfile->extensionName.'/', $up_rule)){
				//判断图片大小
				$filesize=$upfile->getSize();
				if($filesize>10240*10240){
					echo "<script>alert('请上传小于1M的图片');</script>";
					exit;
				}
				if($upfile->saveAs($up_dir.$news_name))
				{
					//echo "<script>alert('ok');</script>";
					$filesplit="";
					$wid=100;
					$wei=100;
					$path=$up_dir.$news_name;
					
					switch($typ)
					{
						case 1:
							$first=strpos($arr['1'],'-');						
							$wid=substr($arr['1'],0,$first);
							$wei=substr($arr['1'],$first+1);
						break;
						case 2:
							$first=strpos($arr['2'],'-');						
							$wid=substr($arr['2'],0,$first);
							$wei=substr($arr['2'],$first+1);
						break;
						case 3:
							$first_line=strpos($arr['3'],'|');
							$arr['1']=substr($arr['3'],0,$first_line);
							$arr['2']=substr($arr['3'],$first_line+1);
							
							$first1=strpos($arr['1'],'-');
							$first2=strpos($arr['2'],'-');
							
							$wid1=substr($arr['1'],0,$first1);
							$wei1=substr($arr['1'],$first1+1);
							
							$wid2=substr($arr['2'],0,$first2);
							$wei2=substr($arr['2'],$first2+1);
						break;
						case 4:
							$first=strpos($arr['4'],'-');						
							$wid=substr($arr['4'],0,$first);
							$wei=substr($arr['4'],$first+1);
						break;
						case 5:
							$first=strpos($arr['5'],'-');						
							$wid=substr($arr['5'],0,$first);
							$wei=substr($arr['5'],$first+1);
						break;
						case 6:
							$first=strpos($arr['6'],'-');						
							$wid=substr($arr['6'],0,$first);
							$wei=substr($arr['6'],$first+1);
						break;
						case 7:
							$first=strpos($arr['7'],'-');						
							$wid=substr($arr['7'],0,$first);
							$wei=substr($arr['7'],$first+1);
						break;
						case 8:
							$first=strpos($arr['8'],'-');						
							$wid=substr($arr['8'],0,$first);
							$wei=substr($arr['8'],$first+1);
						break;
						case 9:
							$first=strpos($arr['9'],'-');						
							$wid=substr($arr['9'],0,$first);
							$wei=substr($arr['9'],$first+1);
						break;
						default:
							
						break;
					}
					//拼接新名称
					if($typ!=3){
						$pathnew=$up_dir.$news_name1.$wid."-".$wei.".".$upfile->extensionName;
					}else{
						$pathnew1=$up_dir.$news_name1.$wid1."-".$wei1.".".$upfile->extensionName;
						$pathnew2=$up_dir.$news_name1.$wid2."-".$wei2.".".$upfile->extensionName;
					}
					
					
					
					$im = null;
					
					if($imagetype == 'gif')
					{
						$im = imagecreatefromgif($path);
					}
					else if ($imagetype == 'jpg')
					{
						$im = imagecreatefromjpeg($path);
					}
					else if ($imagetype == 'png')
					{
						$im = imagecreatefrompng($path);
					}else if($imagetype == 'bmp')
                    {
                        $im =imagecreatefromwbmp($path);
                    }
					
					//生成缩略图
					if($typ!=3){
						$this->resizeImage($im,$wid,$wei,$pathnew,$imagetype);
					}else{
						$this->resizeImage($im,$wid1,$wei1,$pathnew1,$imagetype);
						$this->resizeImage($im,$wid2,$wei2,$pathnew2,$imagetype);
					}
				
					$up_dir=  str_replace($_SERVER['DOCUMENT_ROOT']."","", $up_dir);
					$json=json_encode($news_name);
					
					echo "<script>parent.upload_success('ok','".$up_dir.$news_name."','$obj','$json')</script>";
					
				}else{
					
					echo "<script>parent.upload_success('not','上传错误','$obj')</script>";
				}
			}
		}
		
	}

	private function resizeImage($im, $maxwidth, $maxheight, $name,$filetype) {
	
		//  edit by pan
		
		$pic_width = imagesx ( $im );
		$pic_height = imagesy ( $im );
		$cqdir=0;  //0 x轴  1 y轴
		
		if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) 
		{
			if ($maxwidth && $pic_width > $maxwidth) {
				$widthratio = $maxwidth / $pic_width;
				$resizewidth_tag = true;
			}
			
			if ($maxheight && $pic_height > $maxheight) {
				$heightratio = $maxheight / $pic_height;
				$resizeheight_tag = true;
			}
			
			if ($resizewidth_tag && $resizeheight_tag) {
				if ($widthratio < $heightratio)
				{
					$ratio = $heightratio;
					$cqdir=0;
				}
				else
				{
					$ratio = $widthratio;
					$cqdir=1;
				}
			}
			/*
			if ($resizewidth_tag && ! $resizeheight_tag)
			{
				$ratio = $widthratio;
			}
			if ($resizeheight_tag && ! $resizewidth_tag)
			{
				$ratio = $heightratio;
			}
			*/
			
			$newwidth = (Int)($pic_width * $ratio);
			$newheight = (Int)($pic_height * $ratio);
			
			
			//bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
			
			
			if (function_exists ( "imagecopyresampled" )) {
				$newim = imagecreatetruecolor ( $maxwidth, $maxheight );
				if($cqdir==0)
				{
					//x 轴心裁切
					
					$xpix=(Int)((($pic_width-$maxwidth)*$ratio)/2);
					
					imagecopyresampled ( $newim, $im, 0, 0, $xpix, 0, $newwidth, $newheight, $pic_width, $pic_height );
					
				}else{
					//y 轴心裁切
					
					$ypix=(Int)((($pic_height-$maxheight)*$ratio)/2);
					
					imagecopyresampled ( $newim, $im, 0, 0, 0, $ypix, $newwidth, $newheight, $pic_width, $pic_height );
				}
			} else {
				$newim = imagecreate ( $maxwidth, $maxheight );
				if($cqdir==0)
				{
					//x 轴心裁切
					
					$xpix=(Int)(($pic_width-$maxwidth)/2);
					
					imagecopyresized ( $newim, $im, 0, 0, $xpix, 0, $newwidth, $newheight, $pic_width, $pic_height );
					
				}else{
					//y 轴心裁切
					
					$ypix=(Int)(($pic_height-$maxheight)/2);
					
					imagecopyresized ( $newim, $im, 0, 0, 0, $ypix, $newwidth, $newheight, $pic_width, $pic_height );
				}
				//imagecopyresized ( $newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height );
			}
			
			imagejpeg ( $newim, $name );
			imagedestroy ( $newim );
		} else {
			//$name = $name . $filetype;
			imagejpeg ( $im, $name );
		}
	
	}

	private function uplad_dir(){
	
		$uppath=Yii::app()->params['sitepath']."/upload";
		
		$root_folder= $_SERVER['DOCUMENT_ROOT']. $uppath;
		
		
		if(!file_exists($root_folder))
		{
			mkdir($root_folder);
		}

		$uppath=$root_folder."/".date("Ymd").'/';

		
		if(!file_exists($uppath))
		{
			mkdir($uppath,0777);
		}

		return $uppath;
	}
	
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值