php ajax 檔案上傳實現代碼(1/2)

來源:互聯網
上載者:User

一款完整ajax 檔案上傳功能,我們利用了jquery ajax上傳外掛程式來實現的,下面代碼非常完整。

<html>
<head>
<style>
body{font-size:12px; bgcolor:menu;}
table{font-size:12px;}
</style>
<title></title>
<meta http-equiv="content-stype" content="text/html; charset=gb2312" />
<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 = $('<form  action="" method="post" name="' + formid + '" id="' + formid + '" enctype="multipart/form-data"></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("<div>").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.<?php echo $fromform;?>.<?php echo $fromedit;?>.value=data.msg;
                            alert('上傳成功!');
                            window.close();
      }
     }
    },
    error: function (data, status, e)
    {
     alert(e);
    }
   }
  )
  
  return false;

 }
</script>

 

首頁 1 2 末頁
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.