图片,视频上传工具

  做的一个图片上传工具,后面根据需求 添加了视频上传功能

功能: 图片上传 
判断图片格式,图片大小。

选择图片生成预览图

图片缩放放置

保存图片定义名字生成

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>test upload photo</title>
 
  </head>

    <body>
        <div align="center" style="width:100%; height:300px; font-size:13px">
        <h3>图片上传</h3>
                <font style="letter-spacing:1px" color="#FF0000">*只允许上传jpg|jpeg|png|gif格式的图片</font><br/><br/>
                    <form id="form1" name="form1" method="post" action="index.php">
                        <input type="file" name="fileToUpload" id="fileToUpload" οnchange="javascript:setImagePreviews();fileChange(this);" accept="image/jpg,image/jpeg,image/png,/image/gif"/>
                        <input type="text" name="compressValue" id="compressValue" style="display:none;" />
                        <input type="button" οnclick="uploadBtnClick()" value="上传" /><br/>
                        <input type="hidden" id="imgBase64" name="imgBase64" value="" /><br/>
                        <div id="dd" style="width:100%;display: table-cell; vertical-align:middle;" style=" width:990px;"></div><br>
                        <div id='displayValue' style="word-spacing: normal;word-wrap: break-word;"></div>
                    </form>
        <h3>视频上传</h3>
                <font style="letter-spacing:1px" color="#FF0000">*只允许视频上传</font><br/><br/>
                    <form id="form_vf" name="form_vf" action="t_upload003_vf.php" method="post" enctype="multipart/form-data">
    
                            <input id="filevfid" name="filevf" type="file" >
    
                            <input type="submit" value="上传"><br>

                     </form>


    </body>
</html>


<script type="text/javascript">

        //文件大小判断
        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        function fileChange(target){
            var fileSize = 0;
            if (isIE && !target.files) {    // IE浏览器
                var filePath = target.value; // 获得上传文件的绝对路径
                /**
                 * ActiveXObject 对象为IE和Opera所兼容的JS对象
                 * 用法:
                 *         var newObj = new ActiveXObject( servername.typename[, location])
                 *         其中newObj是必选项。返回 ActiveXObject对象 的变量名。
                 *        servername是必选项。提供该对象的应用程序的名称。
                 *        typename是必选项。要创建的对象的类型或类。
                 *        location是可选项。创建该对象的网络服务器的名称。
                 *\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
                 *     Scripting.FileSystemObject 为 IIS 内置组件,用于操作磁盘、文件夹或文本文件,
                 *    其中返回的 newObj 方法和属性非常的多
                 *    如:var file = newObj.CreateTextFile("C:\test.txt", true) 第二个参表示目标文件存在时是否覆盖
                 *    file.Write("写入内容");    file.Close();
                 */
                var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
                // GetFile(path) 方法从磁盘获取一个文件并返回。
                var file = fileSystem.GetFile(filePath);
                fileSize = file.Size;    // 文件大小,单位:b
            }
            else {    // 非IE浏览器
                fileSize = target.files[0].size;
            }
            var size = fileSize / 1024 / 1024/2;
            if (size > 1) {
                alert("图片不能大于2M,请重新选择");
                clearInputFile(target);
            }
        }









    //下面用于多图片上传预览功能
    function setImagePreviews() {
        //获取选择图片的对象
        var docObj = document.getElementById("fileToUpload");
        //后期显示图片区域的对象
        var dd = document.getElementById("dd");
        dd.innerHTML = "";
        //得到所有的图片文件
        var fileList = docObj.files;
        var patn = /\.jpg$|\.png$|\.jpeg$|\.gif$/i;

        /**
        暂时单张上传
         */


        if (fileList.length>6) {
            alert("不要超过6张");
            clearInputFile(docObj);

        }
        if(!patn.test(docObj.value)){
                alert("请重新选择,注意格式");
                clearInputFile(docObj);
            }

        //循环遍历
        for (var i = 0; i < fileList.length; i++) {    

            //动态添加html元素        
            dd.innerHTML += "<div style='float:left' > <img id='img" + i + "'  /> </div>";
            //获取图片imgi的对象
            var imgObjPreview = document.getElementById("img"+i); 

            if (docObj.files && docObj.files[i]) {
                //火狐下,直接设img属性
                imgObjPreview.style.display = 'block';
                imgObjPreview.style.width = '120px';
                imgObjPreview.style.height = '90px';
                //imgObjPreview.src = docObj.files[0].getAsDataURL();
                //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要以下方式
                imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]);   //获取上传图片文件的物理路径
            }
            else {
                //IE下,使用滤镜
                docObj.select();
                var imgSrc = document.selection.createRange().text;
                //alert(imgSrc)
                var localImagId = document.getElementById("img" + i);
               //必须设置初始大小
                localImagId.style.width = "120px";
                localImagId.style.height = "90px";
                //图片异常的捕捉,防止用户修改后缀来伪造图片
                try {
                    localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                    localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
                }
                catch (e) {
                    alert("您上传的图片格式不正确,请重新选择!");
                    return false;
                }
                imgObjPreview.style.display = 'none';
                document.selection.empty();
            }
        }  
        return true;
    }


    function clearInputFile(f){  
    if(f.value){  
        try{  
            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...  
        }catch(err){  
        }  
        if(f.value){ //for IE5 ~ IE10  
            var form = document.createElement('form'), ref = f.nextSibling, p = f.parentNode;  
            form.appendChild(f);  
            form.reset();  
            p.insertBefore(f,ref);  
        }  
    }  
}  

</script>



<script src="../src/jquery.min.js"></script>
    <script type="text/javascript">
        function uploadBtnClick(){
            var scope = this;
            // change pic to base64
            if(window.File && window.FileReader && window.FileList && window.Blob){ 
                //For Ext :
                //var filefield = me.down('filefield'),
                //    file = filefield.fileInputEl.dom.files[0];    
                var filefield = document.getElementById('fileToUpload'),
                    file = filefield.files[0];
                    
                var compressValue = document.getElementById('compressValue');
                processfile(file,compressValue,uploadCompressFile,scope);
            }else{
                alert("此浏览器不完全支持上载图片");
            }

        }


        function processfile(file,compressValue,uploadCompressFile,scope) {
            var reader = new FileReader();
            reader.onload = function (event) {
                var blob = new Blob([event.target.result]); 
                
                window.URL = window.URL || window.webkitURL;
                var blobURL = window.URL.createObjectURL(blob); 
                
                var image = new Image();
                image.src = blobURL;
                image.onload = function() {
                    var resized = resizeMe(image); 
                    compressValue.value = resized;
                    uploadCompressFile.apply(scope);
                }
            };
            reader.readAsArrayBuffer(file);
        }

        function resizeMe(img) {
            //压缩的大小
            var max_width =800; 
            var max_height =9999; 

            var canvas = document.createElement('canvas');
            var width = img.width;
            var height = img.height;

            if(width > height) {
                if(width > max_width) {
                    height = Math.round(height *= max_width / width);
                    width = max_width;
                }
            } 
            else{
                if(height > max_height) {
                    width = Math.round(width *= max_height / height);
                    height = max_height;
                }
            }
          
            canvas.width = width;
            canvas.height = height;
          
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, width, height);
            //压缩率
            return canvas.toDataURL("image/jpeg",0.7); 
        }

        // call back 
        function uploadCompressFile(){
            //do ajax upload
           document.getElementById('imgBase64').innerHTML  = document.getElementById('compressValue').value;
          $('#imgList2').attr('src',document.getElementById('compressValue').value); //一个空的img--imgList2
          var preview =document.getElementById('compressValue').value;
        //  document.form1.submit();
        //$('#preview99').html(preview);
        //alert(preview);
        //必须对base64字符串进行转码,不然会丢失数据,后台获取保存数据出错
        preview = encodeURIComponent(preview);
        if(preview){
            $.ajax({
                url:"index.php",
                type: "POST",
                data:'imgBase64='+preview,
                success:function(json) {
                    $('#displayValue').html(json);
                    //$('#imgList').attr('src',json);
                    //alert(json);
               },
               error:function(){
                   alert('操作失败,请跟技术联系');
               } 
            });
        }
        /**/
        }
       
    </script>

index.php

<?php
/**
 
      输出生成
        maxwidth 800 图片一张 xx.jpeg
        maxwidth 200 图片一张 s_xx.jpeg 

 */

header('Content-type:text/html;charset=utf-8');
date_default_timezone_set("PRC");
$userid=date("m").date("d");  //用户获取
$destination_folder="x:/www/xxx/xxx/".$userid."/";  //路径位置

$base64_image_content = $_POST['imgBase64'];


//print_r($base64_image_content);
//echo $base64_image_content;
//匹配出图片的格式
//
//
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
		$type = $result[2]; //后缀
		$new_file = $destination_folder; //路径
		if (!file_exists($new_file)) {
			     mkdir($new_file);
		}
		$timename = date("Y").date("m").date("d").date("H").date("i").date("s")."_".rand(100, 999);
		$new_file = $new_file.$timename.".{$type}";//命名

		if (file_put_contents($new_file, base64_decode(str_replace($result[1],'', $base64_image_content)))){
				//echo $base64_image_content;
				//echo '新文件保存成功:', $new_file;
        echo '图片保存成功'.'<br>'.$timename.'.'.$type;
				$im = imagecreatefromjpeg($new_file);
				resizeImage($im,'200','9999','s_'.$timename,'.jpeg',$destination_folder);
				//echo '<br>'."200保存成功";
				//if (resizeImage($new_file,'200','9999','s'.$timename,'.jpeg',$destination_folder)) {
				//	echo "200保存成功";
				//}

		}
		else{
		echo '新文件保存失败';
		}
}




function resizeImage($im,$maxwidth,$maxheight,$name,$filetype,$weizhi) //等比缩放函数
 {
  $pic_width = imagesx($im);
  $pic_height = imagesy($im);
 
  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 = $widthratio;
    else
     $ratio = $heightratio;
   }
 
   if($resizewidth_tag && !$resizeheight_tag)
    $ratio = $widthratio;
   if($resizeheight_tag && !$resizewidth_tag)
    $ratio = $heightratio;
 
   $newwidth = $pic_width * $ratio;
   $newheight = $pic_height * $ratio;
 
   if(function_exists("imagecopyresampled"))
   {
    $newim = imagecreatetruecolor($newwidth,$newheight);//PHP系统函数
      imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP系统函数
   }
   else
   {
    $newim = imagecreate($newwidth,$newheight);
      imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
   }
 
   $name = $name.$filetype;
   imagejpeg($newim,$weizhi.$name);
   imagedestroy($newim);
  }
  else
  {
   $name = $name.$filetype;
   imagejpeg($im,$weizhi.$name);
  }
 }



?>
t_upload003_vf.php
<?php
//require_once "lfile_tools.php";
header("Content-type:text/html;charset=utf-8"); 
date_default_timezone_set("PRC");  //时区
$uptypes=array("avi","mp4","flv","3gp");  //上传文件类型列表 
$max_file_size=31457280;  //上传文件大小限制, 单位BYTE    //30M
$userid=date("m").date("d");  //用户获取
$destination_folder="C:/www/zsbzg/movie/".$userid."/";  //路径位置
$files=getFiles();//图片赋值
foreach ($files as $_FILES ) {

    if($_FILES["error"]){
          echo "<script>alert('请选择视频!');window.location.href='index.html';</script>";
          exit;
    }


    if($_FILES["size"]>$max_file_size) {
          echo $_FILES['name']."<script>alert('视频大于30M!');window.location.href='index.html';</script>";
          exit;
    }

    $ext=getExt($_FILES["name"]);  //后缀名
    if(!in_array($ext, $uptypes)) {
          echo $_FILES['name']."<script>alert('视频格式不正确!');window.location.href='index.html';</script>";
          exit;  
    }

    if(!is_uploaded_file($_FILES['tmp_name'])){   
           echo $_FILES['name']."<script>alert('文件不是通过HTTP POST方式上传上来的!');window.location.href='index.html';</script>";
           exit;
    }  

    //转换编码格式
    //$filename = iconv("UTF-8","gb2312",$filename);

    //判断文件路径是否为空
    if(!file_exists($destination_folder)) {  
          mkdir($destination_folder);  
    } 

      $imgname = $_FILES['tmp_name'];  //文件
      $filename = date("Y").date("m").date("d").date("H").date("i").date("s")."_".rand(100, 999).".".$ext;//命名

    if(move_uploaded_file($imgname,$destination_folder.$filename)){ //文件保存
          //echo $_FILES['name']."</br><font color='#FF0000'>上传成功</font></br>"; 
          echo "<script>alert('视频上传成功!');window.location.href='index.html';</script>";
          exit();
     }



/**

 */
     $tupian = getVideoInfo($destination_folder.$filename);  //视频长度
     $num = ($tupian["size"])/1000/1000 ;   //视频大小
     echo "视频长度:".($tupian['duration']).'(h-m-s-ms)'.'<br>'; 
     echo "视频大小:".sprintf('%.2f', $num)."MB".'<br>';

/**
 
 */
}
      
        

function getFiles(){
  $i=0;
  foreach($_FILES as $file){  
              //因为这时$_FILES是个三维数组,并且上传单文件或多文件时,数组的第一维的类型不同,这样就可以拿来判断上传的是单文件还是多文件  
              if(is_string($file['name'])){  
                    //如果是单文件  
                    $files[$i]=$file;  
                    $i++;  
              }
              elseif(is_array($file['name'])){  
                    //如果是多文件  
                    foreach($file['name'] as $key=>$val){  
                                $files[$i]['name']=$file['name'][$key];  
                                $files[$i]['type']=$file['type'][$key];  
                                $files[$i]['tmp_name']=$file['tmp_name'][$key];  
                                $files[$i]['error']=$file['error'][$key];  
                                $files[$i]['size']=$file['size'][$key];   
                                $i++;  
                    }     
              }  
  }     
    return $files;  
}



function getExt($filename){  
    return strtolower(pathinfo($filename,PATHINFO_EXTENSION));  
}  


function getVideoInfo($file) {
   
  $command = sprintf('D:/ffmpeg/bin/ffmpeg -i "%s" 2>&1', $file);

   
  ob_start();
  passthru($command);
  $info = ob_get_contents();
  ob_end_clean();
   // 使用输出缓冲,获取ffmpeg所有输出内容
  $data = array();
  if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $info, $match)) {
    $data['duration'] = $match[1]; //播放时间
    //$arr_duration = explode(':', $match[1]);
    //$data['seconds'] = $arr_duration[0] * 3600 + $arr_duration[1] * 60 + $arr_duration[2]; //转换播放时间为秒数
    //$data['start'] = $match[2]; //开始时间
    //$data['bitrate'] = $match[3]; //码率(kb)
  }

// if (preg_match("/Video: (.*?), (.*?), (.*?)[,\s]/", $info, $match)) {
//    $data['vcodec'] = $match[1]; //视频编码格式
//    $data['vformat'] = $match[2]; //视频格式
//    $data['resolution'] = $match[3]; //视频分辨率
//    $arr_resolution = explode('x', $match[3]);
//    $data['width'] = $arr_resolution[0];
//    $data['height'] = $arr_resolution[1];
//  }

//  if (preg_match("/Audio: (\w*), (\d*) Hz/", $info, $match)) {
//    $data['acodec'] = $match[1]; //音频编码
//    $data['asamplerate'] = $match[2]; //音频采样频率
//  }
//  if (isset($data['seconds']) && isset($data['start'])) {
//    $data['play_time'] = $data['seconds'] + $data['start']; //实际播放时间
//  }
  $data['size'] = filesize($file); //文件大小
  return $data;
}

 ?>


 <!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
<br>
    <input type="button" οnclick="window.location.href='index.html'" value="返回" />
</form>
</body>
</html>



未完成功能;  多张图片上传。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值