首页 > 语言 > PHP > 正文

ajax php多文件上传代码

2024-09-04 11:45:03
字体:大 中 小
来源:转载
供稿:网友
  1. <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4. <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
  5. <title>ajax php多文件上传代码</title> 
  6. <script> 
  7. (function(){ 
  8.   
  9. var d = document, w = window; 
  10. /** 
  11.  * get element by id 
  12.  */  
  13. function get(element){ 
  14.  if (typeof element == "string") 
  15.   element = d.getelementbyid(element); 
  16.  return element; 
  17. } 
  18. /** 
  19.  * attaches event to a dom element 
  20.  */ 
  21. function addevent(el, type, fn){ 
  22.  if (w.addeventlistener){ 
  23.   el.addeventlistener(type, fn, false); 
  24.  } else if (w.attachevent){ 
  25.   var f = function(){ 
  26.     fn.call(el, w.event); 
  27.   };    
  28.   el.attachevent('on' + type, f) 
  29.  } 
  30. } 
  31.  
  32. /** 
  33.  * creates and returns element from html chunk 
  34.  */ 
  35. var toelement = function(){ 
  36.  var div = d.createelement('div'); 
  37.  return function(html){ 
  38.   div.innerhtml = html; 
  39.   var el = div.childnodes[0]; 
  40.   div.removechild(el); 
  41.   return el; 
  42.  } 
  43. }(); 
  44. function hasclass(ele,cls){ 
  45.  return ele.classname.match(new regexp('(s|^)'+cls+'(s|$)')); 
  46. } 
  47. function addclass(ele,cls) { 
  48.  if (!hasclass(ele,cls)) ele.classname += " "+cls; 
  49. } 
  50. function removeclass(ele,cls) { 
  51.  var reg = new regexp('(s|^)'+cls+'(s|$)'); 
  52.  ele.classname=ele.classname.replace(reg,' '); 
  53. } 
  54. // getoffset function copied from jquery lib (http://jquery.com/) 
  55. if (document.documentelement["getboundingclientrect"]){ 
  56.  // get offset using getboundingclientrect 
  57.  // http://ejohn.org/blog/getboundingclientrect-is-awesome/ 
  58.  var getoffset = function(el){ 
  59.   var box = el.getboundingclientrect(), 
  60.   doc = el.ownerdocument, 
  61.   body = doc.body, 
  62.   docelem = doc.documentelement, 
  63.    
  64.   // for ie  
  65.   clienttop = docelem.clienttop || body.clienttop || 0, 
  66.   clientleft = docelem.clientleft || body.clientleft || 0, 
  67.    
  68.   // in internet explorer 7 getboundingclientrect property is treated as physical, 
  69.   // while others are logical. make all logical, like in ie8.   
  70.    
  71.   zoom = 1; 
  72.    
  73.   if (body.getboundingclientrect) { 
  74.    var bound = body.getboundingclientrect(); 
  75.    zoom = (bound.right - bound.left)/body.clientwidth; 
  76.   } 
  77.    
  78.   if (zoom > 1){ 
  79.    clienttop = 0; 
  80.    clientleft = 0; 
  81.   } 
  82.    
  83.   var top = box.top/zoom + (window.pageyoffset || docelem && docelem.scrolltop/zoom || body.scrolltop/zoom) - clienttop, 
  84.   left = box.left/zoom + (window.pagexoffset|| docelem && docelem.scrollleft/zoom || body.scrollleft/zoom) - clientleft; 
  85.      
  86.   return { 
  87.    top: top, 
  88.    left: left 
  89.   }; 
  90.  } 
  91.   
  92. } else { 
  93.  // get offset adding all offsets  
  94.  var getoffset = function(el){ 
  95.   if (w.jquery){ 
  96.    return jquery(el).offset(); 
  97.   }   
  98.     
  99.   var top = 0, left = 0; 
  100.   do { 
  101.    top += el.offsettop || 0; 
  102.    left += el.offsetleft || 0; 
  103.   } 
  104.   while (el = el.offsetparent); 
  105.    
  106.   return { 
  107.    left: left, 
  108.    top: top 
  109.   }; 
  110.  } 
  111. } 
  112. function getbox(el){ 
  113.  var left, right, top, bottom;  
  114.  var offset = getoffset(el); 
  115.  left = offset.left; 
  116.  top = offset.top; 
  117.        
  118.  right = left + el.offsetwidth; 
  119.  bottom = top + el.offsetheight;   
  120.    
  121.  return { 
  122.   left: left, 
  123.   right: right, 
  124.   top: top, 
  125.   bottom: bottom 
  126.  }; 
  127. } 
  128. /** 
  129.  * crossbrowser mouse coordinates 
  130.  */ 
  131. function getmousecoords(e){   
  132.  // pagex/y is not supported in ie 
  133.  // http://www.quirksmode.org/dom/w3c_css教程om.html    
  134.  if (!e.pagex && e.clientx){ 
  135.   // in internet explorer 7 some properties (mouse coordinates) are treated as physical, 
  136.   // while others are logical (offset). 
  137.   var zoom = 1;  
  138.   var body = document.body; 
  139.    
  140.   if (body.getboundingclientrect) { 
  141.    var bound = body.getboundingclientrect(); 
  142.    zoom = (bound.right - bound.left)/body.clientwidth; 
  143.   } 
  144.   return { 
  145.    x: e.clientx / zoom + d.body.scrollleft + d.documentelement.scrollleft, 
  146.    y: e.clienty / zoom + d.body.scrolltop + d.documentelement.scrolltop 
  147.   }; 
  148.  } 
  149.   
  150.  return { 
  151.   x: e.pagex, 
  152.   y: e.pagey 
  153.  };   
  154. } 
  155. /** 
  156.  * function generates unique id 
  157.  */   
  158. var getuid = function(){ 
  159.  var id = 0; 
  160.  return function(){ 
  161.   return 'valumsajaxupload' + id++; 
  162.  } 
  163. }(); 
  164. function filefrompath(file){ 
  165.  return file.replace(/.*(/|)/, "");    
  166. } 
  167. function getext(file){ 
  168.  return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.tolowercase()) : ''; 
  169. }    
  170. /** 
  171.  * cross-browser way to get xhr object   
  172.  */ 
  173. var getxhr = function(){ 
  174.  var xhr; 
  175.   
  176.  return function(){ 
  177.   if (xhr) return xhr; 
  178.      
  179.   if (typeof xmlhttprequest !== 'undefined') { 
  180.    xhr = new xmlhttprequest(); 
  181.   } else { 
  182.    var v = [ 
  183.     "microsoft.xmlhttp", 
  184.     "msxml2.xmlhttp.5.0", 
  185.     "msxml2.xmlhttp.4.0", 
  186.     "msxml2.xmlhttp.3.0", 
  187.     "msxml2.xmlhttp.2.0"      
  188.    ]; 
  189.     
  190.    for (var i=0; i < v.length; i++){ 
  191.     try { 
  192.      xhr = new activexobject(v[i]); 
  193.      break; 
  194.     } catch (e){} 
  195.    } 
  196.   }     
  197.   return xhr; 
  198.  } 
  199. }(); 
  200. // please use ajaxupload , ajax_upload will be removed in the next version 
  201. ajax_upload = ajaxupload = function(button, options){ 
  202.  if (button.jquery){ 
  203.   // jquery object was passed 
  204.   button = button[0]; 
  205.  } else if (typeof button == "string" && /^#.*/.test(button)){      
  206.   button = button.slice(1);     
  207.  } 
  208.  button = get(button);  
  209.   
  210.  this._input = null; 
  211.  this._button = button; 
  212.  this._disabled = false; 
  213.  this._submitting = false; 
  214.  // variable changes to true if the button was clicked 
  215.  // 3 seconds ago (requred to fix safari on mac error) 
  216.  this._justclicked = false; 
  217.  this._parentdialog = d.body; 
  218.    
  219.  if (window.jquery && jquery.ui && jquery.ui.dialog){ 
  220.   var parentdialog = jquery(this._button).parents('.ui-dialog'); 
  221.   if (parentdialog.length){ 
  222.    this._parentdialog = parentdialog[0]; 
  223.   } 
  224.  }    
  225.       
  226.  this._settings = { 
  227.   // location of the server-side upload script 
  228.   action: 'upload.php',    
  229.   // file upload name 
  230.   name: 'userfile', 
  231.   // additional data to send 
  232.   data: {}, 
  233.   // submit file as soon as it's selected 
  234.   autosubmit: true, 
  235.   // the type of data that you're expecting back from the server. 
  236.   // html and xml are detected automatically. 
  237.   // only useful when you are using json data as a response. 
  238.   // set to "json" in that case.  
  239.   responsetype: false, 
  240.   // location of the server-side script that fixes safari  
  241.   // hanging problem returning "connection: close" header 
  242.   closeconnection: '', 
  243.   // class applied to button when mouse is hovered 
  244.   hoverclass: 'hover',   
  245.   // when user selects a file, useful with autosubmit disabled    
  246.   onchange: function(file, extension){},      
  247.   // callback to fire before file is uploaded 
  248.   // you can return false to cancel upload 
  249.   onsubmit: function(file, extension){}, 
  250.   // fired when file upload is completed 
  251.   // warning! do not use "false" string as a response! 
  252.   oncomplete: function(file, response) {} 
  253.  }; 
  254.  // merge the users options with our defaults 
  255.  for (var i in options) { 
  256.   this._settings[i] = options[i]; 
  257.  } 
  258.   
  259.  this._createinput(); 
  260.  this._rerouteclicks(); 
  261. } 
  262.     
  263. // assigning methods to our class 
  264. ajaxupload.prototype = { 
  265.  setdata : function(data){ 
  266.   this._settings.data = data; 
  267.  }, 
  268.  disable : function(){ 
  269.   this._disabled = true; 
  270.  }, 
  271.  enable : function(){ 
  272.   this._disabled = false; 
  273.  }, 
  274.  // removes instance 
  275.  destroy : function(){ 
  276.   if(this._input){ 
  277.    if(this._input.parentnode){ 
  278.     this._input.parentnode.removechild(this._input); 
  279.    } 
  280.    this._input = null; 
  281.   } 
  282.  },     
  283.  /** 
  284.   * creates invisible file input above the button  
  285.   */ 
  286.  _createinput : function(){ 
  287.   var self = this; 
  288.   var input = d.createelement("input"); 
  289.   input.setattribute('type', 'file'); 
  290.   input.setattribute('name', this._settings.name); 
  291.   var styles = { 
  292.    'position' : 'absolute' 
  293.    ,'margin': '-5px 0 0 -175px' 
  294.    ,'padding': 0 
  295.    ,'width': '220px' 
  296.    ,'height': '30px' 
  297.    ,'fontsize': '14px'         
  298.    ,'opacity': 0 
  299.    ,'cursor': 'pointer' 
  300.    ,'display' : 'none' 
  301.    ,'zindex' :  2147483583 //max zindex supported by opera 9.0-9.2x  
  302.    // strange, i expected 2147483647 
  303.    // doesn't work in ie :( 
  304.    //,'direction' : 'ltr'    
  305.   }; 
  306.   for (var i in styles){ 
  307.    input.style[i] = styles[i]; 
  308.   } 
  309.    
  310.   // make sure that element opacity exists 
  311.   // (ie uses filter instead) 
  312.   if ( ! (input.style.opacity === "0")){ 
  313.    input.style.filter = "alpha(opacity=0)"; 
  314.   } 
  315.         
  316.   this._parentdialog.appendchild(input); 
  317.   addevent(input, 'change', function(){ 
  318.    // get filename from input 
  319.    var file = filefrompath(this.value);  
  320.    if(self._settings.onchange.call(self, file, getext(file)) == false ){ 
  321.     return;     
  322.    }               
  323.    // submit form when value is changed 
  324.    if (self._settings.autosubmit){ 
  325.     self.submit();       
  326.    }       
  327.   }); 
  328.    
  329.   // fixing problem with safari 
  330.   // the problem is that if you leave input before the file select dialog opens 
  331.   // it does not upload the file. 
  332.   // as dialog opens slowly (it is a sheet dialog which takes some time to open) 
  333.   // there is some time while you can leave the button. 
  334.   // so we should not change display to none immediately 
  335.   addevent(input, 'click', function(){ 
  336.    self.justclicked = true; 
  337.    settimeout(function(){ 
  338.     // we will wait 3 seconds for dialog to open 
  339.     self.justclicked = false; 
  340.    }, 2500);    
  341.   });   
  342.    
  343.   this._input = input; 
  344.  }, 
  345.  _rerouteclicks : function (){ 
  346.   var self = this; 
  347.   
  348.   // ie displays 'access denied' error when using this method 
  349.   // other browsers just ignore click() 
  350.   // addevent(this._button, 'click', function(e){ 
  351.   //   self._input.click(); 
  352.   // }); 
  353.      
  354.   var box, dialogoffset = {top:0, left:0}, over = false; 
  355.           
  356.   addevent(self._button, 'mouseo教程ver', function(e){ 
  357.    if (!self._input || over) return; 
  358.     
  359.    over = true; 
  360.    box = getbox(self._button); 
  361.       
  362.    if (self._parentdialog != d.body){ 
  363.     dialogoffset = getoffset(self._parentdialog); 
  364.    }  
  365.   }); 
  366.    
  367.   
  368.   // we can't use mouseout on the button, 
  369.   // because invisible input is over it 
  370.   addevent(document, 'mousemove', function(e){ 
  371.    var input = self._input;    
  372.    if (!input || !over) return; 
  373.     
  374.    if (self._disabled){ 
  375.     removeclass(self._button, self._settings.hoverclass); 
  376.     input.style.display = 'none'; 
  377.     return; 
  378.    }  
  379.            
  380.    var c = getmousecoords(e); 
  381.    if ((c.x >= box.left) && (c.x <= box.right) &&  
  382.    (c.y >= box.top) && (c.y <= box.bottom)){ 
  383.         
  384.     input.style.top = c.y - dialogoffset.top + 'px'; 
  385.     input.style.left = c.x - dialogoffset.left + 'px'; 
  386.     input.style.display = 'block'; 
  387.     addclass(self._button, self._settings.hoverclass); 
  388.          
  389.    } else {   
  390.     // mouse left the button 
  391.     over = false; 
  392.     
  393.     var check = setinterval(function(){ 
  394.      // if input was just clicked do not hide it 
  395.      // to prevent safari bug 
  396.        
  397.      if (self.justclicked){ 
  398.       return; 
  399.      } 
  400.       
  401.      if ( !over ){ 
  402.       input.style.display = 'none';  
  403.      }       
  404.      
  405.      clearinterval(check); 
  406.      
  407.     }, 25); 
  408.       
  409.     removeclass(self._button, self._settings.hoverclass); 
  410.    }    
  411.   });    
  412.     
  413.  }, 
  414.  /** 
  415.   * creates iframe with unique name 
  416.   */ 
  417.  _createiframe : function(){ 
  418.   // unique name 
  419.   // we cannot use gettime, because it sometimes return 
  420.   // same value in safari :( 
  421.   var id = getuid(); 
  422.    
  423.   // remove ie6 "this page contains both secure and nonsecure items" prompt  
  424.   // http://tinyurl.com/77w9wh 
  425.   var iframe = toelement('<iframe src="网页特效:false;" name="' + id + '" />'); 
  426.   iframe.id = id; 
  427.   iframe.style.display = 'none'; 
  428.   d.body.appendchild(iframe);    
  429.   return iframe;       
  430.  }, 
  431.  /** 
  432.   * upload file without refreshing the page 
  433.   */ 
  434.  submit : function(){ 
  435.   var self = this, settings = this._settings;  
  436.       
  437.   if (this._input.value === ''){ 
  438.    // there is no file 
  439.    return; 
  440.   } 
  441.            
  442.   // get filename from input 
  443.   var file = filefrompath(this._input.value);    
  444.   // execute user event 
  445.   if (! (settings.onsubmit.call(this, file, getext(file)) == false)) { 
  446.    // create new iframe for this submission 
  447.    var iframe = this._createiframe(); 
  448.     
  449.    // do not submit if user function returns false           
  450.    var form = this._createform(iframe); 
  451.    form.appendchild(this._input); 
  452.    // a pretty little hack to make uploads not hang in safari. just call this 
  453.    // immediately before the upload is submitted. this does an ajax call to 
  454.    // the server, which returns an empty document with the "connection: close" 
  455.    // header, telling safari to close the active connection. 
  456.    // http://blog.airbladesoftware.com/2007/8/17/note-to-self-prevent-uploads-hanging-in-safari 
  457.    if (settings.closeconnection && /applewebkit|msie/.test(navigator.useragent)){ 
  458.     var xhr = getxhr(); 
  459.     // open synhronous connection 
  460.     xhr.open('get', settings.closeconnection, false); 
  461.     xhr.send(''); 
  462.    } 
  463.     
  464.    form.submit(); 
  465.     
  466.    d.body.removechild(form);     
  467.    form = null; 
  468.    this._input = null; 
  469.     
  470.    // create new input 
  471.    this._createinput(); 
  472.     
  473.    var todeleteflag = false; 
  474.     
  475.    addevent(iframe, 'load', function(e){ 
  476.       
  477.     if (// for safari 
  478.      iframe.src == "javascript:'%3chtml%3e%3c/html%3e';" || 
  479.      // for ff, ie 
  480.      iframe.src == "javascript:'<html></html>';"){       
  481.       
  482.      // first time around, do not delete. 
  483.      if( todeleteflag ){ 
  484.       // fix busy state in ff3 
  485.       settimeout( function() { 
  486.        d.body.removechild(iframe); 
  487.       }, 0); 
  488.      } 
  489.      return; 
  490.     }     
  491.      
  492.     var doc = iframe.contentdocument ? iframe.contentdocument : frames[iframe.id].document; 
  493.     // fixing opera 9.26 
  494.     if (doc.readystate && doc.readystate != 'complete'){ 
  495.      // opera fires load event multiple times 
  496.      // even when the dom is not ready yet 
  497.      // this fix should not affect other browsers 
  498.      return; 
  499.     } 
  500.      
  501.     // fixing opera 9.64 
  502.     if (doc.body && doc.body.innerhtml == "false"){ 
  503.      // in opera 9.64 event was fired second time 
  504.      // when body.innerhtml changed from false  
  505.      // to server response approx. after 1 sec 
  506.      return;     
  507.     } 
  508.      
  509.     var response; 
  510.           
  511.     if (doc.xmldocument){ 
  512.      // response is a xml document ie property 
  513.      response = doc.xmldocument; 
  514.     } else if (doc.body){ 
  515.      // response is html document or plain text 
  516.      response = doc.body.innerhtml; 
  517.      if (settings.responsetype && settings.responsetype.tolowercase() == 'json'){ 
  518.       // if the document was sent as 'application/javascript' or 
  519.       // 'text/javascript', then the browser wraps教程 the text in a <pre> 
  520.       // tag and performs html encoding on the contents.  in this case, 
  521.       // we need to pull the original text content from the text node's 
  522.       // nodevalue property to retrieve the unmangled content. 
  523.       // note that ie6 only understands text/html 
  524.       if (doc.body.firstchild && doc.body.firstchild.nodename.touppercase() == 'pre'){ 
  525.        response = doc.body.firstchild.firstchild.nodevalue; 
  526.       } 
  527.       if (response) { 
  528.        response = window["eval"]("(" + response + ")"); 
  529.       } else { 
  530.        response = {}; 
  531.       } 
  532.      } 
  533.     } else { 
  534.      // response is a xml document 
  535.      var response = doc; 
  536.     } 
  537.                     
  538.     settings.oncomplete.call(self, file, response); 
  539.        
  540.     // reload blank page, so that reloading main page 
  541.     // does not re-submit the post. also, remember to 
  542.     // delete the frame 
  543.     todeleteflag = true; 
  544.      
  545.     // fix ie mixed content issue 
  546.     iframe.src = "javascript:'<html></html>';";            
  547.    }); 
  548.   
  549.   } else { 
  550.    // clear input to allow user to select same file 
  551.    // doesn't work in ie6 
  552.    // this._input.value = ''; 
  553.    d.body.removechild(this._input);     
  554.    this._input = null; 
  555.     
  556.    // create new input 
  557.    this._createinput();       
  558.   } 
  559.  },   
  560.  /** 
  561.   * creates form, that will be submitted to iframe 
  562.   */ 
  563.  _createform : function(iframe){ 
  564.   var settings = this._settings; 
  565.    
  566.   // method, enctype must be specified here 
  567.   // because changing this attr on the fly is not allowed in ie 6/7   
  568.   var form = toelement('<form method="post" enctype="multipart/form-data"></form>'); 
  569.   form.style.display = 'none'; 
  570.   form.action = settings.action; 
  571.   form.target = iframe.name; 
  572.   d.body.appendchild(form); 
  573.    
  574.   // create hidden input element for each data key 
  575.   for (var prop in settings.data){ 
  576.    var el = d.createelement("input"); 
  577.    el.type = 'hidden'; 
  578.    el.name = prop; 
  579.    el.value = settings.data[prop]; 
  580.    form.appendchild(el); 
  581.   }    
  582.   return form; 
  583.  }  
  584. }; 
  585. })(); 
  586. </script> 
  587. </head> 
  588. <body> 
  589. <p id="errorremind"></p> 
  590. <input id="unloadpic" type="button" value="上传图片" /> 
  591. <ol id="uploadedname"></ol> 
  592. <script type="text/javascript" src="../js/ajaxupload.js"></script> 
  593. <script type="text/javascript"> 
  594. window.onload = function(){ 
  595.  var obtn = document.getelementbyid("unloadpic"); 
  596.  var oshow = document.getelementbyid("uploadedname"); 
  597.  var oremind = document.getelementbyid("errorremind");  
  598.  new ajaxupload(obtn,{ 
  599.   action:"file_upload.php", 
  600.   name:"upload", 
  601.   onsubmit:function(file,ext){ 
  602.    if(ext && /^(jpg|jpeg|png|gif)$/.test(ext)){ 
  603.     //ext是后缀名 
  604.     obtn.value = "正在上传…"; 
  605.     obtn.disabled = "disabled"; 
  606.    }else{  
  607.     oremind.style.color = "#ff3300"; 
  608.     oremind.innerhtml = "不支持非图片格式!"; 
  609.     return false; 
  610.    } 
  611.   }, 
  612.   oncomplete:function(file,response){ 
  613.    obtn.disabled = ""; 
  614.    obtn.value = "再上传一张图片"; 
  615.    oremind.innerhtml = ""; 
  616.    var newchild =  document.createelement("li"); 
  617.    newchild.innerhtml = file; 
  618.    oshow.appendchild(newchild); 
  619.   } 
  620.  }); 
  621. }; 
  622. </script> 
  623. </body> 
  624. </html> 
  625. <?php #file_upload.php 2009-11-06 
  626. //开源代码Vevb.com 
  627.  $file_path = '../../../uploads/'; 
  628.  $file_up = $file_path.basename($_files['upload']['name']); 
  629.  if(move_uploaded_file($_files['upload']['tmp_name'],$file_up)){ 
  630.   echo 'success';  
  631.  }else{ 
  632.   echo 'fail';  
  633.  } 
  634. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表