【www.gdgbn.com--jquery】

一款完整ajax 文件上传功能,我们利用了jquery ajax上传插件来实现的,下面代码非常完整。






<script type="text/网页特效" src="http://code.google.com/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" >

jquery.extend({
 

    createuploadiframe: function(id, uri)
 {
   //create frame
            var frameid = "juploadframe" + id;
           
            if(window.activexobject) {
                var io = document.createelement("<iframe id="" + frameid + "" name="" + frameid + "" />");
                if(typeof uri== "boolean"){
                    io.src = "javascript:false";
                }
                else if(typeof uri== "string"){
                    io.src = uri;
                }
            }
            else {
                var io = document.createelement("iframe");
                io.id = frameid;
                io.name = frameid;
            }
            io.style.position = "absolute";
            io.style.top = "-1000px";
            io.style.left = "-1000px";

            document.body.appendchild(io);

            return io   
    },
    createuploadform: function(id, fileelementid)
 {
  //create form 
  var formid = "juploadform" + id;
  var fileid = "juploadfile" + id;
  var form = $(""); 
  var oldelement = $("#" + fileelementid);
  var newelement = $(oldelement).clone();
  $(oldelement).attr("id", fileid);
  $(oldelement).before(newelement);
  $(oldelement).appendto(form);
  //set attributes
  $(form).css教程("position", "absolute");
  $(form).css("top", "-1200px");
  $(form).css("left", "-1200px");
  $(form).appendto("body");  
  return form;
    },

    ajaxfileupload: function(s) {
        // todo introduce global settings, allowing the client to modify them for all requests, not only timeout  
        s = jquery.extend({}, jquery.ajaxsettings, s);
        var id = new date().gettime()       
  var form = jquery.createuploadform(id, s.fileelementid);
  var io = jquery.createuploadiframe(id, s.secureuri);
  var frameid = "juploadframe" + id;
  var formid = "juploadform" + id;  
        // watch for a new set of requests
        if ( s.global && ! jquery.active++ )
  {
   jquery.event.trigger( "ajaxstart" );
  }           
        var requestdone = false;
        // create the request object
        var xml = {}  
        if ( s.global )
            jquery.event.trigger("ajaxsend", [xml, s]);
        // wait for a response to come back
        var uploadcallback = function(istimeout)
  {   
   var io = document.getelementbyid(frameid);
            try
   {    
    if(io.contentwindow)
    {
      xml.responsetext = io.contentwindow.document.body?io.contentwindow.document.body.innerhtml:null;
                  xml.responsexml = io.contentwindow.document.xmldocument?io.contentwindow.document.xmldocument:io.contentwindow.document;
     
    }else if(io.contentdocument)
    {
      xml.responsetext = io.contentdocument.document.body?io.contentdocument.document.body.innerhtml:null;
                 xml.responsexml = io.contentdocument.document.xmldocument?io.contentdocument.document.xmldocument:io.contentdocument.document;
    }      
            }catch(e)
   {
    jquery.handleerror(s, xml, null, e);
   }
            if ( xml || istimeout == "timeout")
   {    
                requestdone = true;
                var status;
                try {
                    status = istimeout != "timeout" ? "success" : "error";
                    // make sure that the request was successful or notmodified
                    if ( status != "error" )
     {
                        // process the data (runs the xml through httpdata regardless of callback)
                        var data = jquery.uploadhttpdata( xml, s.datatype );   
                        // if a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
   
                        // fire the global callback
                        if( s.global )
                            jquery.event.trigger( "ajaxsuccess", [xml, s] );
                    } else
                        jquery.handleerror(s, xml, status);
                } catch(e)
    {
                    status = "error";
                    jquery.handleerror(s, xml, status, e);
                }

                // the request was completed
                if( s.global )
                    jquery.event.trigger( "ajaxcomplete", [xml, s] );

                // handle the global ajax counter
                if ( s.global && ! --jquery.active )
                    jquery.event.trigger( "ajaxstop" );

                // process result
                if ( s.complete )
                    s.complete(xml, status);

                jquery(io).unbind()

                settimeout(function()
         { try
          {
           $(io).remove();
           $(form).remove(); 
           
          } catch(e)
          {
           jquery.handleerror(s, xml, null, e);
          }         

         }, 100)

                xml = null

            }
        }
        // timeout checker
        if ( s.timeout > 0 )
  {
            settimeout(function(){
                // check to see if the request is still happening
                if( !requestdone ) uploadcallback( "timeout" );
            }, s.timeout);
        }
        try
  {
           // var io = $("#" + frameid);
   var form = $("#" + formid);
   $(form).attr("action", s.url);
   $(form).attr("method", "post");
   $(form).attr("target", frameid);
            if(form.encoding)
   {
                form.encoding = "multipart/form-data";    
            }
            else
   {    
                form.enctype = "multipart/form-data";
            }   
            $(form).submit();

        } catch(e)
  {   
            jquery.handleerror(s, xml, null, e);
        }
        if(window.attachevent){
            document.getelementbyid(frameid).attachevent("onload", uploadcallback);
        }
        else{
            document.getelementbyid(frameid).addeventlistener("load", uploadcallback, false);
        }   
        return {abort: function () {}}; 

    },

    uploadhttpdata: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responsexml : r.responsetext;
        // if the type is "script", eval it in global context
        if ( type == "script" )
            jquery.globaleval( data );
        // get the javascript object, if json is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jquery("").html(data).evalscripts();
   //alert($("param", data).each(function(){alert($(this).attr("value"));}));
        return data;
    }
})


</script>
<script type="text/javascript">
 function ajaxfileupload()
 {
  $("#loading")
  .ajaxstart(function(){
   $(this).show();
  })
  .ajaxcomplete(function(){
   $(this).hide();
  });

  $.ajaxfileupload
  (
   {
    url:"do_ajax_file_upload.php教程",
    secureuri:false,
    fileelementid:"filetoupload",
    datatype: "json",
    success: function (data, status)
    {
     if(typeof(data.error) != "undefined")
     {
      if(data.error != "")
      {
       alert(data.error);
      }else
      {
                            window.opener.document...value=data.msg;
                            alert("上传成功!");
                            window.close();
      }
     }
    },
    error: function (data, status, e)
    {
     alert(e);
    }
   }
  )
  
  return false;

 }
</script>

 

 

 




上传中,请稍后……



文件上传

请选择要上传的文件:




允许上传的文件类型:gif,jpg,jpge,png




 
 





do_ajax_file_upload.php

$fileelementname = "filetoupload";
if(isset($_files["filetoupload"])){
    if($_files["filetoupload"]["name"] <> ""){
        require_once ("upload_class.php");
        $savepath = "../upfiles/{$_session["suploaddir"]}";
        makedirectory($savepath);
        $fileformat = array("gif","jpg","jpge","png","swf");
        $maxsize = 0;
        $overwrite = 0;
        $f = new clsupload( $savepath, $fileformat, $maxsize, $overwrite);
        $f->setthumb(0);
        if (!$f->run("filetoupload",1)){
        $error.=$f->errmsg();
        }
       $uparrays=$f->getinfo();
       foreach ($uparrays as $uparray) {
           $msg.=$uparray[path].$uparray[savename].",";
       }
       if($msg!=""){$msg=substr($msg,0,-1);}
       echo "{";
       echo    "error: "" . $error . "",n";
       echo    "msg: "" . $msg . ""n";
       echo "}";
    }
}
function makedirectory($directoryname) {
       $directoryname = str_replace("","/",$directoryname);
       $dirnames = explode("/", $directoryname);
       $total = count($dirnames) ;
       $temp = "";
       for($i=0; $i<$total; $i++) {
         $temp .= $dirnames[$i]."/";
         if (!is_dir($temp)) {
            $oldmask = umask(0);
            if (!mkdir($temp, 0777)) exit("不能建立目录 $temp");
            umask($oldmask);
         }
       }
       return true;
}

下面代码保存成upload_class.php
"
class clsupload{
    var $savename;// 保存名
    var $savepath;// 保存路径
    var $fileformat = array("gif","jpg","doc","application/octet-stream");// 文件格式&mime限定
    var $overwrite = 0;// 覆盖模式
    var $maxsize = 0;// 文件最大字节
    var $ext;// 文件扩展名
    var $thumb = 0;// 是否生成缩略图
    var $thumbwidth = 130;// 缩略图宽
    var $thumbheight = 130;// 缩略图高
    var $thumbprefix = "s_";// 缩略图前缀
    var $errno;// 错误代号
    var $returnarray= array();// 所有文件的返回信息
    var $returninfo= array();// 每个文件返回信息

    function clsupload($savepath, $fileformat="",$maxsize = 0, $overwrite = 0) {
           $this->setsavepath($savepath);
           $this->setfileformat($fileformat);
           $this->setmaxsize($maxsize);
           $this->setoverwrite($overwrite);
           $this->setthumb($this->thumb, $this->thumbwidth,$this->thumbheight);
           $this->errno = 0;
    }

    // 上传
    function run($fileinput,$changename = 1){
           if(isset($_files[$fileinput])){
             $filearr = $_files[$fileinput];
             if(is_array($filearr["name"])){//上传同文件域名称多个文件
                for($i = 0; $i < count($filearr["name"]); $i++){
                       $ar["tmp_name"] = $filearr["tmp_name"][$i];
                       $ar["name"] = $filearr["name"][$i];
                       $ar["type"] = $filearr["type"][$i];
                       $ar["size"] = $filearr["size"][$i];
                       $ar["error"] = $filearr["error"][$i];
                       $this->getext($ar["name"]);//取得扩展名,赋给$this->ext,下次循环会更新
                       $this->setsavename($changename == 1 ? "" : $ar["name"]);//设置保存文件名
                       if($this->copyfile($ar)){
                         $this->returnarray[] =   $this->returninfo;
                       }else{
                         $this->returninfo["error"] = $this->errmsg();
                         $this->returnarray[] =   $this->returninfo;
                       }
                }
                return $this->errno ?   false :   true;
             }else{//上传单个文件
                $this->getext($filearr["name"]);//取得扩展名
                $this->setsavename($changename == 1 ? "" : $filearr["name"]);//设置保存文件名
                if($this->copyfile($filearr)){
                       $this->returnarray[] =   $this->returninfo;
                }else{
                       $this->returninfo["error"] = $this->errmsg();
                       $this->returnarray[] =   $this->returninfo;
                }
                return $this->errno ?   false :   true;
             }
             return false;
           }else{
             $this->errno = 10;
             return false;
           }
    }
    // 单个文件上传
    function copyfile($filearray){
           $this->returninfo = array();
           // 返回信息
           $this->returninfo["name"] = $filearray["name"];
           $this->returninfo["savename"] = $this->savename;
           $this->returninfo["size"] = number_format( ($filearray["size"])/1024 , 0, ".", " ");//以kb为单位
           $this->returninfo["type"] = $filearray["type"];
           $this->returninfo["path"] = $this->savepath;
           // 检查文件格式
           if (!$this->validateformat()){
             $this->errno = 11;
             return false;
           }
           // 检查目录是否可写
           if(!@is_writable($this->savepath)){
             $this->errno = 12;
             return false;
           }
           // 如果不允许覆盖,检查文件是否已经存在
           if($this->overwrite == 0 && @file_exists($this->savepath.$filearray["name"])){
             $this->errno = 13;
             return false;
           }
           // 如果有大小限制,检查文件是否超过限制
           if ($this->maxsize != 0 ){
             if ($filearray["size"] > $this->maxsize){
                $this->errno = 14;
                return false;
             }
           }
           // 文件上传
           if(!@copy($filearray["tmp_name"], $this->savepath.$this->savename)){
             $this->errno = $filearray["error"];
             return false;
           }elseif( $this->thumb ){//创建缩略图
             $createfunction = "imagecreatefrom".($this->ext == "jpg" ? "jpeg" : $this->ext);
             $savefunction = "image".($this->ext == "jpg" ? "jpeg" : $this->ext);
             if (strtolower($createfunction) == "imagecreatefromgif"
                && !function_exists("imagecreatefromgif")) {
                $this->errno = 16;
                return false;
             } elseif (strtolower($createfunction) == "imagecreatefromjpeg"
                && !function_exists("imagecreatefromjpeg")) {
                $this->errno = 17;
                return false;
             } elseif (!function_exists($createfunction)) {
                $this->errno = 18;
                return false;
             }
               
             $original = @$createfunction($this->savepath.$this->savename);
             if (!$original) {$this->errno = 19; return false;}
             $originalheight = imagesy($original);
             $originalwidth = imagesx($original);
             $this->returninfo["originalheight"] = $originalheight;
             $this->returninfo["originalwidth"] = $originalwidth;
             if (($originalheight < $this->thumbheight
                && $originalwidth < $this->thumbwidth)) {
                // 如果比期望的缩略图小,那只copy
                copy($this->savepath.$this->savename,
                       $this->savepath.$this->thumbprefix.$this->savename);
             } else {
                if( $originalwidth > $this->thumbwidth ){// 宽 > 设定宽度
                       $thumbwidth = $this->thumbwidth ;
                       $thumbheight = $this->thumbwidth * ( $originalheight / $originalwidth );
                       if($thumbheight > $this->thumbheight){//高 > 设定高度
                         $thumbwidth = $this->thumbheight * ( $thumbwidth / $thumbheight );
                         $thumbheight = $this->thumbheight ;
                       }
                }elseif( $originalheight > $this->thumbheight ){//高 > 设定高度
                       $thumbheight = $this->thumbheight ;
                       $thumbwidth = $this->thumbheight * ( $originalwidth / $originalheight );
                       if($thumbwidth > $this->thumbwidth){//宽 > 设定宽度
                         $thumbheight = $this->thumbwidth * ( $thumbheight / $thumbwidth );
                         $thumbwidth = $this->thumbwidth ;
                       }
                }
                if ($thumbwidth == 0) $thumbwidth = 1;
                if ($thumbheight == 0) $thumbheight = 1;
                $createdthumb = imagecreatetruecolor($thumbwidth, $thumbheight);
                if ( !$createdthumb ) {$this->errno = 20; return false;}
                if ( !imagecopyresampled($createdthumb, $original, 0, 0, 0, 0,
                       $thumbwidth, $thumbheight, $originalwidth, $originalheight) )
                       {$this->errno = 21; return false;}
                if ( !$savefunction($createdthumb,
                       $this->savepath.$this->thumbprefix.$this->savename) )
                       {$this->errno = 22; return false;}
             }
           }
           // 删除临时文件
           if(!@$this->del($filearray["tmp_name"])){
             return false;
           }
           return true;
    }
    // 文件格式检查,mime检测
    function validateformat(){
           if(!is_array($this->fileformat)
             || in_array(strtolower($this->ext), $this->fileformat)
             || in_array(strtolower($this->returninfo["type"]), $this->fileformat) )
             return true;
           else
             return false;
    }
    //获取文件扩展名
    function getext($filename){
           $ext = explode(".", $filename);
           $ext = $ext[count($ext) - 1];
           $this->ext = strtolower($ext);
    }
    //设置上传文件的最大字节限制 0:表示无限制
    function setmaxsize($maxsize){
           $this->maxsize = $maxsize;
    }
    //设置文件格式限定
    function setfileformat($fileformat){
           if(is_array($fileformat)){$this->fileformat = $fileformat ;}
    }
    //设置覆盖模式  1:允许覆盖 0:禁止覆盖
    function setoverwrite($overwrite){
           $this->overwrite = $overwrite;
    }
    //设置保存路径
    function setsavepath($savepath){
           $this->savepath = substr( str_replace("","/", $savepath) , -1) == "/" ? $savepath : $savepath."/";
    }
    //设置缩略图
    function setthumb($thumb, $thumbwidth = 0,$thumbheight = 0){
           $this->thumb = $thumb;
           if($thumbwidth) $this->thumbwidth = $thumbwidth;
           if($thumbheight) $this->thumbheight = $thumbheight;
    }
    //设置文件保存名
    function setsavename($savename){
           if ($savename == ""){   // 如果未设置文件名,则生成一个随机文件名
             $name = date("ymdhis")."_".rand(100,999).".".$this->ext;
           } else {
             $name = $savename;
           }
           $this->savename = $name;
    }
    //删除文件
    function del($filename){
           if(!@unlink($filename)){
             $this->errno = 15;
             return false;
           }
           return true;
    }
    // 返回上传文件的信息
    function getinfo(){
           return $this->returnarray;
    }
    // 得到错误信息
    function errmsg(){
           $uploadclasserror = array(
             0 =>"there is no error, the file uploaded with success. ",
             1 =>"the uploaded file exceeds the upload_max_filesize directive in php.ini.",
             2 =>"the uploaded file exceeds the max_file_size that was specified in the html form.",
             3 =>"the uploaded file was only partially uploaded. ",
             4 =>"no file was uploaded. ",
             6 =>"missing a temporary folder. introduced in php 4.3.10 and php 5.0.3. ",
             7 =>"failed to write file to disk. introduced in php 5.1.0. ",
             10 =>"input name is not unavailable!",
             11 =>"the uploaded file is unallowable!",
             12 =>"directory unwritable!",
             13 =>"file exist already!",
             14 =>"file is too big!",
             15 =>"delete file unsuccessfully!",
             16 =>"your version of php does not appear to have gif thumbnailing support.",
             17 =>"your version of php does not appear to have jpeg thumbnailing support.",
             18 =>"your version of php does not appear to have pictures thumbnailing support.",
             19 =>"an error occurred while attempting to copy the source image .
                       your version of php (".phpversion().") may not have this image type support.",
             20 =>"an error occurred while attempting to create a new image.",
             21 =>"an error occurred while copying the source image to the thumbnail image.",
             22 =>"an error occurred while saving the thumbnail image to the filesystem.
                       are you sure that php has been configured with both read and write access on this folder?",
                );
           if ($this->errno == 0)
             return false;
           else
             return $uploadclasserror[$this->errno];
    }
}

本文来源:http://www.gdgbn.com/wangyezhizuo/28179/