ajax php多文件上传代码

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>ajax php教程多文件上传代码</title>
<script>
(function(){
 
var d = document, w = window;

/**
 * get element by id
 */ 
function get(element){
 if (typeof element == "string")
  element = d.getelementbyid(element);
 return element;
}

/**
 * attaches event to a dom element
 */
function addevent(el, type, fn){
 if (w.addeventlistener){
  el.addeventlistener(type, fn, false);
 } else if (w.attachevent){
  var f = function(){
    fn.call(el, w.event);
  };   
  el.attachevent('on' + type, f)
 }
}

/**
 * creates and returns element from html chunk
 */
var toelement = function(){
 var div = d.createelement('div');
 return function(html){
  div.innerhtml = html;
  var el = div.childnodes[0];
  div.removechild(el);
  return el;
 }
}();

function hasclass(ele,cls){
 return ele.classname.match(new regexp('(s|^)'+cls+'(s|$)'));
}
function addclass(ele,cls) {
 if (!hasclass(ele,cls)) ele.classname += " "+cls;
}
function removeclass(ele,cls) {
 var reg = new regexp('(s|^)'+cls+'(s|$)');
 ele.classname=ele.classname.replace(reg,' ');
}

// getoffset function copied from jquery lib (http://jquery.com/)
if (document.documentelement["getboundingclientrect"]){
 // get offset using getboundingclientrect
 // http://ejohn.org/blog/getboundingclientrect-is-awesome/
 var getoffset = function(el){
  var box = el.getboundingclientrect(),
  doc = el.ownerdocument,
  body = doc.body,
  docelem = doc.documentelement,
  
  // for ie
  clienttop = docelem.clienttop || body.clienttop || 0,
  clientleft = docelem.clientleft || body.clientleft || 0,
  
  // in internet explorer 7 getboundingclientrect property is treated as physical,
  // while others are logical. make all logical, like in ie8.  
  
  zoom = 1;
  
  if (body.getboundingclientrect) {
   var bound = body.getboundingclientrect();
   zoom = (bound.right - bound.left)/body.clientwidth;
  }
  
  if (zoom > 1){
   clienttop = 0;
   clientleft = 0;
  }
  
  var top = box.top/zoom + (window.pageyoffset || docelem && docelem.scrolltop/zoom || body.scrolltop/zoom) - clienttop,
  left = box.left/zoom + (window.pagexoffset|| docelem && docelem.scrollleft/zoom || body.scrollleft/zoom) - clientleft;
    
  return {
   top: top,
   left: left
  };
 }
 
} else {
 // get offset adding all offsets
 var getoffset = function(el){
  if (w.jquery){
   return jquery(el).offset();
  }  
   
  var top = 0, left = 0;
  do {
   top += el.offsettop || 0;
   left += el.offsetleft || 0;
  }
  while (el = el.offsetparent);
  
  return {
   left: left,
   top: top
  };
 }
}

function getbox(el){
 var left, right, top, bottom; 
 var offset = getoffset(el);
 left = offset.left;
 top = offset.top;
      
 right = left + el.offsetwidth;
 bottom = top + el.offsetheight;  
  
 return {
  left: left,
  right: right,
  top: top,
  bottom: bottom
 };
}

/**
 * crossbrowser mouse coordinates
 */
function getmousecoords(e){  
 // pagex/y is not supported in ie
 // http://www.quirksmode.org/dom/w3c_css教程om.html   
 if (!e.pagex && e.clientx){
  // in internet explorer 7 some properties (mouse coordinates) are treated as physical,
  // while others are logical (offset).
  var zoom = 1; 
  var body = document.body;
  
  if (body.getboundingclientrect) {
   var bound = body.getboundingclientrect();
   zoom = (bound.right - bound.left)/body.clientwidth;
  }

  return {
   x: e.clientx / zoom + d.body.scrollleft + d.documentelement.scrollleft,
   y: e.clienty / zoom + d.body.scrolltop + d.documentelement.scrolltop
  };
 }
 
 return {
  x: e.pagex,
  y: e.pagey
 };  

}
/**
 * function generates unique id
 */  
var getuid = function(){
 var id = 0;
 return function(){
  return 'valumsajaxupload' + id++;
 }
}();

function filefrompath(file){
 return file.replace(/.*(/|)/, "");   
}

function getext(file){
 return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.tolowercase()) : '';
}   

/**
 * cross-browser way to get xhr object 
 */
var getxhr = function(){
 var xhr;
 
 return function(){
  if (xhr) return xhr;
    
  if (typeof xmlhttprequest !== 'undefined') {
   xhr = new xmlhttprequest();
  } else {
   var v = [
    "microsoft.xmlhttp",
    "msxml2.xmlhttp.5.0",
    "msxml2.xmlhttp.4.0",
    "msxml2.xmlhttp.3.0",
    "msxml2.xmlhttp.2.0"     
   ];
   
   for (var i=0; i < v.length; i++){
    try {
     xhr = new activexobject(v[i]);
     break;
    } catch (e){}
   }
  }    

  return xhr;
 }
}();

// please use ajaxupload , ajax_upload will be removed in the next version
ajax_upload = ajaxupload = function(button, options){
 if (button.jquery){
  // jquery object was passed
  button = button[0];
 } else if (typeof button == "string" && /^#.*/.test(button)){     
  button = button.slice(1);    
 }
 button = get(button); 
 
 this._input = null;
 this._button = button;
 this._disabled = false;
 this._submitting = false;
 // variable changes to true if the button was clicked
 // 3 seconds ago (requred to fix safari on mac error)
 this._justclicked = false;
 this._parentdialog = d.body;
  
 if (window.jquery && jquery.ui && jquery.ui.dialog){
  var parentdialog = jquery(this._button).parents('.ui-dialog');
  if (parentdialog.length){
   this._parentdialog = parentdialog[0];
  }
 }   
     
 this._settings = {
  // location of the server-side upload script
  action: 'upload.php',   
  // file upload name
  name: 'userfile',
  // additional data to send
  data: {},
  // submit file as soon as it's selected
  autosubmit: true,
  // the type of data that you're expecting back from the server.
  // html and xml are detected automatically.
  // only useful when you are using json data as a response.
  // set to "json" in that case.
  responsetype: false,
  // location of the server-side script that fixes safari
  // hanging problem returning "connection: close" header
  closeconnection: '',
  // class applied to button when mouse is hovered
  hoverclass: 'hover',  
  // when user selects a file, useful with autosubmit disabled   
  onchange: function(file, extension){},     
  // callback to fire before file is uploaded
  // you can return false to cancel upload
  onsubmit: function(file, extension){},
  // fired when file upload is completed
  // warning! do not use "false" string as a response!
  oncomplete: function(file, response) {}
 };

 // merge the users options with our defaults
 for (var i in options) {
  this._settings[i] = options[i];
 }
 
 this._createinput();
 this._rerouteclicks();
}
   
// assigning methods to our class
ajaxupload.prototype = {
 setdata : function(data){
  this._settings.data = data;
 },
 disable : function(){
  this._disabled = true;
 },
 enable : function(){
  this._disabled = false;
 },
 // removes instance
 destroy : function(){
  if(this._input){
   if(this._input.parentnode){
    this._input.parentnode.removechild(this._input);
   }
   this._input = null;
  }
 },    
 /**
  * creates invisible file input above the button
  */
 _createinput : function(){
  var self = this;
  var input = d.createelement("input");
  input.setattribute('type', 'file');
  input.setattribute('name', this._settings.name);
  var styles = {
   'position' : 'absolute'
   ,'margin': '-5px 0 0 -175px'
   ,'padding': 0
   ,'width': '220px'
   ,'height': '30px'
   ,'fontsize': '14px'        
   ,'opacity': 0
   ,'cursor': 'pointer'
   ,'display' : 'none'
   ,'zindex' :  2147483583 //max zindex supported by opera 9.0-9.2x
   // strange, i expected 2147483647
   // doesn't work in ie :(
   //,'direction' : 'ltr'   
  };
  for (var i in styles){
   input.style[i] = styles[i];
  }
  
  // make sure that element opacity exists
  // (ie uses filter instead)
  if ( ! (input.style.opacity === "0")){
   input.style.filter = "alpha(opacity=0)";
  }
       
  this._parentdialog.appendchild(input);

  addevent(input, 'change', function(){
   // get filename from input
   var file = filefrompath(this.value); 
   if(self._settings.onchange.call(self, file, getext(file)) == false ){
    return;    
   }              
   // submit form when value is changed
   if (self._settings.autosubmit){
    self.submit();      
   }      
  });
  
  // fixing problem with safari
  // the problem is that if you leave input before the file select dialog opens
  // it does not upload the file.
  // as dialog opens slowly (it is a sheet dialog which takes some time to open)
  // there is some time while you can leave the button.
  // so we should not change display to none immediately
  addevent(input, 'click', function(){
   self.justclicked = true;
   settimeout(function(){
    // we will wait 3 seconds for dialog to open
    self.justclicked = false;
   }, 2500);   
  });  
  
  this._input = input;
 },
 _rerouteclicks : function (){
  var self = this;
 
  // ie displays 'access denied' error when using this method
  // other browsers just ignore click()
  // addevent(this._button, 'click', function(e){
  //   self._input.click();
  // });
    
  var box, dialogoffset = {top:0, left:0}, over = false;
         
  addevent(self._button, 'mouseo教程ver', function(e){
   if (!self._input || over) return;
   
   over = true;
   box = getbox(self._button);
     
   if (self._parentdialog != d.body){
    dialogoffset = getoffset(self._parentdialog);
   } 
  });
  
 
  // we can't use mouseout on the button,
  // because invisible input is over it
  addevent(document, 'mousemove', function(e){
   var input = self._input;   
   if (!input || !over) return;
   
   if (self._disabled){
    removeclass(self._button, self._settings.hoverclass);
    input.style.display = 'none';
    return;
   } 
          
   var c = getmousecoords(e);

   if ((c.x >= box.left) && (c.x <= box.right) &&
   (c.y >= box.top) && (c.y <= box.bottom)){
       
    input.style.top = c.y - dialogoffset.top + 'px';
    input.style.left = c.x - dialogoffset.left + 'px';
    input.style.display = 'block';
    addclass(self._button, self._settings.hoverclass);
        
   } else {  
    // mouse left the button
    over = false;
   
    var check = setinterval(function(){
     // if input was just clicked do not hide it
     // to prevent safari bug
     
     if (self.justclicked){
      return;
     }
     
     if ( !over ){
      input.style.display = 'none'; 
     }      
    
     clearinterval(check);
    
    }, 25);
     

    removeclass(self._button, self._settings.hoverclass);
   }   
  });   
   
 },
 /**
  * creates iframe with unique name
  */
 _createiframe : function(){
  // unique name
  // we cannot use gettime, because it sometimes return
  // same value in safari :(
  var id = getuid();
  
  // remove ie6 "this page contains both secure and nonsecure items" prompt
  // http://tinyurl.com/77w9wh
  var iframe = toelement('<iframe src="网页特效:false;" name="' + id + '" />');
  iframe.id = id;
  iframe.style.display = 'none';
  d.body.appendchild(iframe);   
  return iframe;      
 },
 /**
  * upload file without refreshing the page
  */
 submit : function(){
  var self = this, settings = this._settings; 
     
  if (this._input.value === ''){
   // there is no file
   return;
  }
          
  // get filename from input
  var file = filefrompath(this._input.value);   

  // execute user event
  if (! (settings.onsubmit.call(this, file, getext(file)) == false)) {
   // create new iframe for this submission
   var iframe = this._createiframe();
   
   // do not submit if user function returns false          
   var form = this._createform(iframe);
   form.appendchild(this._input);

   // a pretty little hack to make uploads not hang in safari. just call this
   // immediately before the upload is submitted. this does an ajax call to
   // the server, which returns an empty document with the "connection: close"
   // header, telling safari to close the active connection.
   // http://blog.airbladesoftware.com/2007/8/17/note-to-self-prevent-uploads-hanging-in-safari
   if (settings.closeconnection && /applewebkit|msie/.test(navigator.useragent)){
    var xhr = getxhr();
    // open synhronous connection
    xhr.open('get', settings.closeconnection, false);
    xhr.send('');
   }
   
   form.submit();
   
   d.body.removechild(form);    
   form = null;
   this._input = null;
   
   // create new input
   this._createinput();
   
   var todeleteflag = false;
   
   addevent(iframe, 'load', function(e){
     
    if (// for safari
     iframe.src == "javascript:'%3chtml%3e%3c/html%3e';" ||
     // for ff, ie
     iframe.src == "javascript:'<html></html>';"){      
     
     // first time around, do not delete.
     if( todeleteflag ){
      // fix busy state in ff3
      settimeout( function() {
       d.body.removechild(iframe);
      }, 0);
     }
     return;
    }    
    
    var doc = iframe.contentdocument ? iframe.contentdocument : frames[iframe.id].document;

    // fixing opera 9.26
    if (doc.readystate && doc.readystate != 'complete'){
     // opera fires load event multiple times
     // even when the dom is not ready yet
     // this fix should not affect other browsers
     return;
    }
    
    // fixing opera 9.64
    if (doc.body && doc.body.innerhtml == "false"){
     // in opera 9.64 event was fired second time
     // when body.innerhtml changed from false
     // to server response approx. after 1 sec
     return;    
    }
    
    var response;
         
    if (doc.xmldocument){
     // response is a xml document ie property
     response = doc.xmldocument;
    } else if (doc.body){
     // response is html document or plain text
     response = doc.body.innerhtml;
     if (settings.responsetype && settings.responsetype.tolowercase() == 'json'){
      // if the document was sent as 'application/javascript' or
      // 'text/javascript', then the browser wraps教程 the text in a <pre>
      // tag and performs html encoding on the contents.  in this case,
      // we need to pull the original text content from the text node's
      // nodevalue property to retrieve the unmangled content.
      // note that ie6 only understands text/html
      if (doc.body.firstchild && doc.body.firstchild.nodename.touppercase() == 'pre'){
       response = doc.body.firstchild.firstchild.nodevalue;
      }
      if (response) {
       response = window["eval"]("(" + response + ")");
      } else {
       response = {};
      }
     }
    } else {
     // response is a xml document
     var response = doc;
    }
                   
    settings.oncomplete.call(self, file, response);
      
    // reload blank page, so that reloading main page
    // does not re-submit the post. also, remember to
    // delete the frame
    todeleteflag = true;
    
    // fix ie mixed content issue
    iframe.src = "javascript:'<html></html>';";           
   });
 
  } else {
   // clear input to allow user to select same file
   // doesn't work in ie6
   // this._input.value = '';
   d.body.removechild(this._input);    
   this._input = null;
   
   // create new input
   this._createinput();      
  }
 },  
 /**
  * creates form, that will be submitted to iframe
  */
 _createform : function(iframe){
  var settings = this._settings;
  
  // method, enctype must be specified here
  // because changing this attr on the fly is not allowed in ie 6/7  
  var form = toelement('<form method="post" enctype="multipart/form-data"></form>');
  form.style.display = 'none';
  form.action = settings.action;
  form.target = iframe.name;
  d.body.appendchild(form);
  
  // create hidden input element for each data key
  for (var prop in settings.data){
   var el = d.createelement("input");
   el.type = 'hidden';
   el.name = prop;
   el.value = settings.data[prop];
   form.appendchild(el);
  }   
  return form;
 } 
};
})();
</script>
</head>

<body>
<p id="errorremind"></p>
<input id="unloadpic" type="button" value="上传图片" />
<ol id="uploadedname"></ol>

<script type="text/javascript" src="../js/ajaxupload.js"></script>
<script type="text/javascript">
window.onload = function(){
 var obtn = document.getelementbyid("unloadpic");
 var oshow = document.getelementbyid("uploadedname");
 var oremind = document.getelementbyid("errorremind"); 
 new ajaxupload(obtn,{
  action:"file_upload.php",
  name:"upload",
  onsubmit:function(file,ext){
   if(ext && /^(jpg|jpeg|png|gif)$/.test(ext)){
    //ext是后缀名
    obtn.value = "正在上传…";
    obtn.disabled = "disabled";
   }else{ 
    oremind.style.color = "#ff3300";
    oremind.innerhtml = "不支持非图片格式!";
    return false;
   }
  },
  oncomplete:function(file,response){
   obtn.disabled = "";
   obtn.value = "再上传一张图片";
   oremind.innerhtml = "";
   var newchild =  document.createelement("li");
   newchild.innerhtml = file;
   oshow.appendchild(newchild);
  }
 });
};
</script>
</body>
</html>

<?php #file_upload.php 2009-11-06
 $file_path = '../../../uploads/';
 $file_up = $file_path.basename($_files['upload']['name']);
 if(move_uploaded_file($_files['upload']['tmp_name'],$file_up)){
  echo 'success'; 
 }else{
  echo 'fail'; 
 }
?>

时间: 2024-11-05 12:17:03

ajax php多文件上传代码的相关文章

php+ajax实现图片文件上传实例代码

方法一,利用jquery ajaxfileupload.js文件上传 其实就是实现无刷新式的文件上传.可采用IFRAME文件上传原理. 实际上在用PHP上传文件时...只能用$_FILES形式,但是若我们只是单一的用JS方式取其ID,如<input id='img' type='file'>..document.getElementById('img').value或者jquery形式的$("#img")都是不能正真实际上传的(但是还是有很多人这样做,刚开始时我也是). 可

ajax+php 无刷新文件上传代码

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.111cn.net/1999/xhtml"> <head> <meta http-equiv="conte

php Ajax实现异步文件上传的代码

php教程 ajax实现异步文件上传的代码 1:取得file对象 2:读取2进制数据 3:模拟http请求,把数据发送出去(这里通常比较麻烦) 在forefox下使用 xmlhttprequest 对象的 sendasbinary 方法发送数据: 4:完美实现 遇到的问题 目前仅有 firefox 可以正确上传文件.(chrome也可以采google.gears上传) 对于从firefox和chrome下读取到的文件数据好像不一样(不知道是否是调试工具的原因) chrome以及其他高级浏览器没有

基于Ajax技术实现文件上传带进度条_AJAX相关

1.概述 在实际的Web应该开发或网站开发过程中,经常需要实现文件上传的功能.在文件上传过程中,经常需要用户进行长时间的等待,为了让用户及时了解上传进度,可以在上传文件的同时,显示文件的上传进度条.运行本实例,如图1所示,访问文件上传页面,单击"浏览"按钮选择要上传的文件,注意文件不能超过50MB,否则系统将给出错误提示.选择完要上传的文件后,单击"提交"按钮,将会上传文件并显示上传进度. 2.技术要点 主要是应用开源的Common-FileUpload组件来实现分

基于ajax html实现文件上传技巧总结_AJAX相关

引语:大家都知道,html中上传文件就一个input,type=file就搞定了.但是,这个标签的样式,实在不值得提点什么,要改动他的样式,恐怕也是较难的.但是其实挺简单,今天就来说说上传文件小技巧吧! 1. 怎样自定义样式? 1).只管按照自己喜欢看到的样式去定义即可,如<a href='javascript:;' class='upload-button'></a>,可以是背景图片效果,可以是文字指示,总之想怎么改怎么改!有了按钮,还需要一个文件名容器,用来存放选择上传文件时的

jQuery+ajax简单实现文件上传的方法_jquery

本文实例讲述了jQuery+ajax简单实现文件上传的方法.分享给大家供大家参考,具体如下: 可以通过ajax来提交表单,而不会刷新页面.主要使用的方法是 $("#formID").ajaxSubmit()方法. 1.要引入js插件 需要下载的附件:jquery.form.js 2.页面代码: <script src="project/js/jquery.form.js" type="text/javascript"></scr

asp.net+jquery 文件上传代码(1/2)

asp教程.net+jquery 文件上传代码 <%@ page language="c#" contenttype="text/html" responseencoding="gb2312" %> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml

php iframe 无刷新文件上传代码

其它原理很简单,利用form表单的target属性和iframe来实现的,打开为iframe试就行了,返回就利用js判断php教程运行后返回的参数是不是成功 一.上传文件的一个php方法. 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失败,则返回空字符串. php代码     function uploadfile($file) {         // 上传路径     $destinationpath = "./upload/&qu

基于Ajax技术实现文件上传带进度条

1.概述 在实际的Web应该开发或网站开发过程中,经常需要实现文件上传的功能.在文件上传过程中,经常需要用户进行长时间的等待,为了让用户及时了解上传进度,可以在上传文件的同时,显示文件的上传进度条.运行本实例,如图1所示,访问文件上传页面,单击"浏览"按钮选择要上传的文件,注意文件不能超过50MB,否则系统将给出错误提示.选择完要上传的文件后,单击"提交"按钮,将会上传文件并显示上传进度. 2.技术要点 主要是应用开源的Common-FileUpload组件来实现分