Ajax php multiple File upload code

Source: Internet
Author: User
Tags php tutorial unique id blank page

<!doctype HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/ Xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>ajax PHP Tutorial Multi-File Upload code </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 &gt; 1) {


ClientTop = 0;


ClientLeft = 0;


}





var top = box.top/zoom + (Window.pageyoffset | | Docelem &amp;&amp; docelem.scrolltop/zoom | | body.scrolltop/zoom)-Client Top


left = Box.left/zoom + (window.pagexoffset| | Docelem &amp;&amp; docelem.scrollleft/zoom | | body.scrollleft/zoom)-Client Left





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 isn't supported in IE
 //http://www.quirksmode.org/dom/w3c_css tutorial om.html   
 if (!e.pagex && e.clientx) {
  //in Internet Explorer 7 some properties (mouse coordinates) AR E 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 &lt; v.length; i++) {


try {


XHR = new ActiveXObject (V[i]);


Break


catch (e) {}


}


}

return XHR;
}
}();

Please use Ajaxupload, ajax_upload'll 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" &amp;&amp;/^#.*/.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 is clicked


3 seconds ago (requred to fix Safari on Mac error)


this._justclicked = false;


This._parentdialog = D.body;





if (window.jquery &amp;&amp; jquery.ui &amp;&amp; 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 is expecting back to the server.


HTML and XML are detected automatically.


Only useful while you are using JSON data as a response.


Set to ' JSON ' in ' the ' 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 the file is uploaded


can return false to cancel upload


Onsubmit:function (file, extension) {},


Fired when the file upload is completed


warning! Don't 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 this 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)


The There is some the button, while you can leave.


So we should don't change display to none immediately


Addevent (Input, ' click ', function () {


Self.justclicked = true;


settimeout (function () {


We'll 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 tutorial ver ', function (e) {


if (!self._input | |) 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 &gt;= box.left) &amp;&amp; (c.x &lt;= box.right) &amp;&amp;


(C.y &gt;= box.top) &amp;&amp; (c.y &lt;= 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 does 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 and 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 (' &lt;iframe src= "web effect: false;" Name= "' + ID + '"/&gt; ');


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 a Ajax call to


The server, which returns a 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 &amp;&amp;/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: ' &lt;html&gt;&lt;/html&gt; ';" {





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 &amp;&amp; doc.readystate!= ' complete ') {


Opera fires Load event multiple times


Even when the DOM isn't ready yet


This fix should isn't affect other browsers


Return


}





Fixing opera 9.64


if (doc.body &amp;&amp; doc.body.innerhtml = = "false") {


In opera 9.64 event is fired second time


When body.innerhtml changed from false


To server Response approx 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 &amp;&amp; settings.responsetype.tolowercase () = = ' json ') {


If the document was sent as ' application/javascript ' or


' Text/javascript ', then the browser wraps tutorial the text in a &lt;pre&gt;


Tag and performs HTML encoding on the contents. In the case,


We need to pull the original text content from the text node ' s


NodeValue to retrieve the unmangled content.


Note This IE6 only understands text/html


if (Doc.body.firstchild &amp;&amp; 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: ' &lt;html&gt;&lt;/html&gt; ';";


});





} 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'll be submitted to IFRAME


*/


_createform:function (IFRAME) {


var settings = this._settings;





method, Enctype must is specified here


Because changing this attr on the fly isn't allowed in IE 6/7


var form = toelement (' &lt;form method= ' post ' enctype= ' multipart/form-data ' &gt;&lt;/form&gt; ');


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;


}


};


})();


&lt;/script&gt;


&lt;/head&gt;

<body>
<p id= "Errorremind" ></p>
<input id= "unloadpic" type= "button" value= "Upload picture"/>
<ol id= "Uploadedname" ></ol>

&lt;script type= "Text/javascript" src= ". /js/ajaxupload.js "&gt;&lt;/script&gt;


&lt;script type= "Text/javascript" &gt;


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 &amp;&amp;/^ (jpg|jpeg|png|gif) $/.test (ext)) {


Ext is the suffix name


Obtn.value = "uploading ...";


obtn.disabled = "Disabled";


}else{


Oremind.style.color = "#ff3300";


oremind.innerhtml = "does not support non-picture Format!" ";


return false;


}


},


Oncomplete:function (file,response) {


obtn.disabled = "";


Obtn.value = "Upload a picture again";


oremind.innerhtml = "";


var newchild = document.createelement ("Li");


newchild.innerhtml = file;


Oshow.appendchild (newchild);


}


});


};


&lt;/script&gt;


&lt;/body&gt;


&lt;/html&gt;

<?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 ';  
 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.