当前位置:首页 > PHP教程 > php上传下载 > 列表

PHP Ajax上传文件实例,ajaxfileupload.js

发布:smiling 来源: PHP粉丝网  添加日期:2014-08-27 14:31:08 浏览: 评论:0 

讲过利用jquery ajax与php实现图片上传,下面我介绍利用php ajax实现各种文件无刷新上传,直接放实例希望给各位同学有帮助,可以批量进行添加上传,简单方便,代码如下:

  1. <script type="text/javascript" src="jquery-1.5.1.min.js"></script> 
  2.  
  3.  
  4. <script    type="text/javascript" > 
  5.  
  6.  
  7. jQuery.extend({ 
  8.      
  9.  
  10.  
  11.     createUploadIframe: function(id, uri) 
  12.     { 
  13.            //create frame 
  14.             var frameId = 'jUploadFrame' + id; 
  15.             var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'
  16.            if(window.ActiveXObject) 
  17.            { 
  18.                 if(typeof uri== 'boolean'){ 
  19.                   iframeHtml += ' src="' + 'javascript:false' + '"'
  20.  
  21.  
  22.                 } 
  23.                 else if(typeof uri== 'string'){ 
  24.                   iframeHtml += ' src="' + uri + '"'
  25.  
  26.  
  27.                 }  
  28.            } 
  29.            iframeHtml += ' />'
  30.            jQuery(iframeHtml).appendTo(document.body); 
  31.  
  32.  
  33.             return jQuery('#' + frameId).get(0);         
  34.     }, 
  35.     createUploadForm: function(id, fileElementId, data) 
  36.     { 
  37.        //create form  
  38.        var formId = 'jUploadForm' + id; 
  39.        var fileId = 'jUploadFile' + id; 
  40.        var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');    
  41.        if(data) 
  42.        { 
  43.            for(var i in data) 
  44.            { 
  45.               jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); 
  46.            }           
  47.        }       
  48.        var oldElement = jQuery('#' + fileElementId); 
  49.        var newElement = jQuery(oldElement).clone(); 
  50.        jQuery(oldElement).attr('id', fileId); 
  51.        jQuery(oldElement).before(newElement); 
  52.        jQuery(oldElement).appendTo(form); 
  53.  
  54.        //set attributes 
  55.        jQuery(form).css('position''absolute'); 
  56.        jQuery(form).css('top''-1200px'); 
  57.        jQuery(form).css('left''-1200px'); 
  58.        jQuery(form).appendTo('body');      
  59.        return form; 
  60.     }, 
  61.  
  62.  
  63.     ajaxFileUpload: function(s) { 
  64.         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout       
  65.         s = jQuery.extend({}, jQuery.ajaxSettings, s); 
  66.         var id = new Date().getTime()         
  67.        var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data)); 
  68.        var io = jQuery.createUploadIframe(id, s.secureuri); 
  69.        var frameId = 'jUploadFrame' + id; 
  70.        var formId = 'jUploadForm' + id;        
  71.         // Watch for a new set of requests 
  72.         if ( s.global && ! jQuery.active++ ) 
  73.        { 
  74.            jQuery.event.trigger( "ajaxStart" ); 
  75.        }             
  76.         var requestDone = false
  77.         // Create the request object 
  78.         var xml = {}    
  79.         if ( s.global ) 
  80.             jQuery.event.trigger("ajaxSend", [xml, s]); 
  81.         // Wait for a response to come back 
  82.         var uploadCallback = function(isTimeout) 
  83.        {           
  84.            var io = document.getElementById(frameId); 
  85.             try  
  86.            {              
  87.               if(io.contentWindow) 
  88.               { 
  89.                    xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null
  90.                    xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; 
  91.                     
  92.               }else if(io.contentDocument) 
  93.               { 
  94.                    xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null
  95.                   xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; 
  96.               }                     
  97.             }catch(e) 
  98.            { 
  99.               jQuery.handleError(s, xml, null, e); 
  100.            } 
  101.             if ( xml || isTimeout == "timeout")  
  102.            {              
  103.                 requestDone = true
  104.                 var status; 
  105.                 try { 
  106.                     status = isTimeout != "timeout" ? "success" : "error"
  107.                     // Make sure that the request was successful or notmodified 
  108.                     if ( status != "error" ) 
  109.                   { 
  110.                         // process the data (runs the xml through httpData regardless of callback) 
  111.                         var data = jQuery.uploadHttpData( xml, s.dataType );     
  112.                         // If a local callback was specified, fire it and pass it the data 
  113.                         if ( s.success ) 
  114.                             s.success( data, status ); 
  115.      
  116.                         // Fire the global callback 
  117.                         if( s.global ) 
  118.                             jQuery.event.trigger( "ajaxSuccess", [xml, s] ); 
  119.                     } else 
  120.                         jQuery.handleError(s, xml, status); 
  121.                 } catch(e)  
  122.               { 
  123.                     status = "error"
  124.                     jQuery.handleError(s, xml, status, e); 
  125.                 } 
  126.  
  127.  
  128.                 // The request was completed 
  129.                 if( s.global ) 
  130.                     jQuery.event.trigger( "ajaxComplete", [xml, s] ); 
  131.  
  132.  
  133.                 // Handle the global AJAX counter 
  134.                 if ( s.global && ! --jQuery.active ) 
  135.                     jQuery.event.trigger( "ajaxStop" ); 
  136.  
  137.  
  138.                 // Process result 
  139.                 if ( s.complete ) 
  140.                     s.complete(xml, status); 
  141.  
  142.  
  143.                 jQuery(io).unbind() 
  144.  
  145.  
  146.                 setTimeout(function() 
  147.                                 {   try  
  148.                                    { 
  149.                                        jQuery(io).remove(); 
  150.                                        jQuery(form).remove();    
  151.                                         
  152.                                    } catch(e)  
  153.                                    { 
  154.                                        jQuery.handleError(s, xml, null, e); 
  155.                                    }                                
  156.  
  157.  
  158.                                 }, 100) 
  159.  
  160.  
  161.                 xml = null 
  162.  
  163.  
  164.             } 
  165.         } 
  166.         // Timeout checker 
  167.         if ( s.timeout > 0 )  
  168.        { 
  169.             setTimeout(function(){ 
  170.                 // Check to see if the request is still happening 
  171.                 if( !requestDone ) uploadCallback( "timeout" ); 
  172.             }, s.timeout); 
  173.         } 
  174.         try  
  175.        { 
  176.  
  177.  
  178.            var form = jQuery('#' + formId); 
  179.            jQuery(form).attr('action', s.url); 
  180.            jQuery(form).attr('method''POST'); 
  181.            jQuery(form).attr('target', frameId); 
  182.             if(form.encoding) 
  183.            { 
  184.               jQuery(form).attr('encoding''multipart/form-data');               
  185.             } 
  186.             else 
  187.            {    
  188.               jQuery(form).attr('enctype''multipart/form-data');         
  189.             }         
  190.             jQuery(form).submit(); 
  191.  
  192.  
  193.         } catch(e)  
  194.        {           
  195.             jQuery.handleError(s, xml, null, e); 
  196.         } 
  197.         
  198.        jQuery('#' + frameId).load(uploadCallback ); 
  199.         return {abort: function () {}};   
  200.  
  201.  
  202.     }, 
  203.  
  204.  
  205.     uploadHttpData: function( r, type ) { 
  206.         var data = !type; 
  207.         data = type == "xml" || data ? r.responseXML : r.responseText; 
  208.         // If the type is "script", eval it in global context 
  209.         if ( type == "script" ) 
  210.             jQuery.globalEval( data ); 
  211.         // Get the JavaScript object, if JSON is used. 
  212.         if ( type == "json" ) 
  213.             eval( "data = " + data ); 
  214.         // evaluate scripts within html 
  215.         if ( type == "html" ) 
  216.             jQuery("<div>").html(data).evalScripts(); 
  217.  
  218.  
  219.         return data; 
  220.     } 
  221. }) 
  222.  
  223. </script> 
  224.  
  225.  
  226. <form id="upform" action="" method="post" enctype="multipart/form-data"
  227.     <input id='fname' size='80' /><br> <input type="file" name="file1" 
  228.        id="file1" size="30" /> <input type="button" value="上传" 
  229.        onclick="return ajaxFileUpload();" /> <span id="msg" 
  230.        style="display: none">UpLoading...</span> 
  231. </form> 
  232.  
  233.  
  234. <script type="text/javascript"
  235. var str = ''
  236. function ajaxFileUpload(){   
  237.     $("#msg"
  238.     .ajaxStart(function(){ 
  239.        $(this).show(); 
  240.     }); 
  241.     /* 
  242.     .ajaxComplete(function(){ 
  243.        $(this).hide(); 
  244.     }); 
  245.     */ 
  246.     $.ajaxFileUpload( 
  247.     { 
  248.        url:'up_deal.php'
  249.        secureuri:false
  250.        fileElementId:'file1'
  251.        dataType: 'text'
  252.        //data:{name:'qinmi', id:'123'}, 
  253.        success: function(data){ 
  254.               if(data=='error'){ 
  255.                   $('#msg').html("<span style='color:red'>上传失败</span>"); 
  256.               }else
  257.                   $('#msg').html("<span style='color:green'>上传成功</span>"); 
  258.                   str +=  data+'@'
  259.                   $('#fname').val(str); 
  260.               } 
  261.            } 
  262.        } 
  263.     ); 
  264.     return false
  265. </script> 

 

up_deal.php,代码如下:

  1. <?php 
  2. if ((($_FILES["file1"]["type"] == "image/gif"
  3. || ($_FILES["file1"]["type"] == "image/jpeg"
  4. || ($_FILES["file1"]["type"] == "image/bmp"
  5. || ($_FILES["file1"]["type"] == "image/pjpeg")) 
  6. && ($_FILES["file1"]["size"] < 100000)){//100KB 
  7.     $extend = explode(".",$_FILES["file1"]["name"]); 
  8.     $key = count($extend)-1; 
  9.     $ext = ".".$extend[$key]; 
  10.     $newfile = time().$ext
  11.     //开源代码phpfensi.com 
  12.     if(!file_exists('upload')){mkdir('upload');} 
  13.     move_uploaded_file($_FILES["file1"]["tmp_name"],"upload/" . $newfile); 
  14.     @unlink($_FILES['file1']); 
  15.     echo $newfile
  16. }else { 
  17.     echo 'error'
  18. ?> 

Tags: PHP Ajax上传文件 ajaxfileupload js

分享到: