How to implement file upload ajaxupload.js

This article mainly introduces how AjaxUPload.js implements file upload, has a certain reference value, and friends needed can be referred to. I hope that everyone has a big gain after reading this article. Let’s take a look at you with everyone.

AjaxUPload.js file code for your reference, the specific content is as follows

  / ** * ajax upload (http://valums.com/ajax-upload) /) * Copyright (c) Andris Valums * license (http://valums.com/mit-license/) * Thanks to Gary Haran, David Mark, Corey Burns and Others for Contributions * / (Function () {/ * Global window * / / * JSLINT BROWSER: TRUE, DEVEL: TRUE, undef: true, Nomen: True, Bitwise: true, regexp: true, newcap: true, immed: true * / / / ** * Wrapper for Firebug's Console.log * / function log () {if (configuration "! = 'undefined' && typeof (console.log) == 'function') {Array.Prototype.unshift.call (arguments, '[ajax upload] '); console.log (Array.Prototype.Join.call (arguments, ''));}} / ** * attach at to a dom element. * @Param {Element} el * @Param Type Event Name * @Param Fn Callback this Refers to the passed element * / Function Addevent (EL, TYPE, FN) {IF (El.AddeventListener) {El.AddeventListener (Type, Fn, False);} else if (el.attachevent) {El.attachevent ('on' + type, function () {Fn.call (EL);});} Else {throw new error ('not supported or dom not loaded ");}} / ** * attachs resize event to a window, limited * number of event fas Fired. Fires ONLY When Encounteres * delay of 100 after series of events. * * Some Browsers Fire Event Multiple Times when resizing * http://www.quirksmode.org/dom/events/resize.html * * @Param Fn Callback this REFers to the passed element * / function address; addevent (window, 'resize ", function () {if (timeout) {cleartment {iarout (timeout);} Timeout = setTimeout (FN, 100);}) ;} // Needs more testing, will be rewriten for next version // 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.getboundingclient (); var doc = El.ownerDocument; var body = doc.body; var docelem = doc .documentelement; // for ie var clienttop = docelem.clienttop || body.clienttop || 0; varclieft = 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 var zoom = 1;.. if (body.getBoundingClientRect) { Var bound = body.getBoundingClientRect (); zoom = (bound.right - bound.left) / body.clientwidth;} if (zoom> 1) {clienttop = 0; clientlet = 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 Add All Offsets Var GetofFset = function (el) {var top = 0, left = 0; do {TOP + = El.offSettop || 0; LEFT + = El.offsetleft || 0; EL = El.offSetParent;} While (EL); Return {Left: Left, Top: Top};};} / ** * Returns Left, Top, Right and Bottom Properties Describing The Border-Box, * in Pixels, With Top-Left Relative to the Body * @Param { Element} el * @return {Object} Contains Left, Top, Right, Bottom * / 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; RTURN {Left: Left, Right: Right, Top: Top, Bottom: Bottom};} / ** * Helper Takes Object Literal * and add all properties to element.style * @param {Element} el * @param {Object} styles * / function addStyles (el, styles) {for (var name in styles) {if (styles.hasOwnProperty (name) ) {el.style [name] = styles [name];}.}} / ** * Function places an absolutely positioned * element on top of the specified element * copying position and dimentions * @param {Element} from * @param {ELEMENT} to * / function copylayout (from, to) {var box = getBox (from); addstyles (to, {position: 'Absolute', Left: Box.Left + 'PX', Top: Box.top + ' PX ', width: from.offsetwidth +' px ', height: from.offsetheight +' px '});} / ** * creates and returns element from html chunk * Usess innerhtml to create an elEment * / var tolement = (function () {var p = document.createElement ('p'); returnif {p.innerhtml = html; var = p.firstchild; return p.RemoveChild (EL); };}) (); / ** * function generates unique id * @return unique id * / var getuid = (function () {var id = 0; returnial () {return 'valumsajaxupload' + ID ++;}; ) (); / ** * Get file name from path * @Param {string} file path to file * @return filename * / function fileFromPath (file) {return file.replace (/.* (\\) /, "");} / ** * get file extension lowercase * @Param {string} file name * @Return file excenStion * / function getext (file) {return (-1! == file.indexof ('.' )))? file.replace (/.*[.]/, ''): ';} fuNCTION Hasclass (EL, NAME) {var RE = New Regexp ('\\ b' + name + '\\ b'); Return Re.Test (El.className);} Function AddClass (EL, NAME) {IF ( Hasclass (EL, NAME)) {El.className + = '' + name;}} Function RemoveClass (EL, NAME) {var RE = New Regexp ('\\ b' + name + '\\ b'); el.className = el.className.replace (re, '');} function removeNode (el) {el.parentNode.removeChild (el);} / ** * Easy styling and uploading * @constructor * @param button An element you want convert to * upload button. Tested dimentions up to 500x500px * @param {Object} options See defaults below. * / window.AjaxUpload = function (button, options) {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, // Class applied to button when mouse is hovered hoverClass: 'hover ', // Class applied to button when AU is disabled disabledClass:' disabled ', // When user selects a file, useful with autoSubmit disabled // You can return false to cancel upload 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) {IF (Options.hasownProperty (i)) {this._settings [i] = options [i];}} // Button ISN't Necessary A DOM ELEMENT IF (Button .jquery) {// jQuery Object Was passed button = button [0];} else f (typeof button == "string") {if (/^) {// if jQuery User passes #elementId do not break it button = button.slice (1);} button = document.getElementById (button);} if (!! button || button.nodeType == 1) {throw new Error ( "Please make Sure That you're passin");} if (Button.NodeName.touppercase () == 'a') {// disable link addevent (Button, 'Click', Function (E) {IF (E && E.PREVENTDEFAULT) {e .preventdefault ();} else if (window.event) {window.Event.ReturnValue = false;}});} // Dom Element this._button = button; // Dom Element this._input = null; // if disabled clicking on button will not do anything this._disabled = false; // if the button was disabled before refresh if will remain // disabled in FireFox, let's fix it this.enable (); this._rerouteClicks ();}; // Assigning methods to oor class ajaxupload.prototype = {setdata: function (data) {this._settings.data = data;}, disable: function () {addclass (tHis._Button, this._settings.disabledclass; this._disabled = true; var nodename = this._button.nodename.touppercase (); if (nodename == 'INPUT' || nodename == 'Button') {THIS. _button.setAttribute ( 'disabled', 'disabled');} // hide input if (this._input) {// We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn 't change if it // has display none when user selects a file this._input.parentNode.style.visibility =' hidden ';}}, enable: function () {removeClass (this._button, this._settings.disabledClass) THIS._BUTTON.Removettribute ('Disabled'); this._disabled = false;}, / ** * Creates Invisible File Input * That Will Hover Above The ButtoN * 

* / _CreateInput: function () {var self = this; var input = document.createElement ("infut"); input.settribute ('type', 'file'); input .SetaTribute ('Name', this._settings.name); AddStyles (INPUT, {'Position': 'Absolute', // in Opera Only 'Browse' Button // IS Clickable and It Is Located At // The Right Side of the input 'right': 0, 'margin': 0, 'padding': 0, 'fontsize': '480px', 'cursor': 'Pointer'}; var p = document.createElement ("p") AddStyles (p, {'Display': 'Block', 'Position': 'Absolute', 'OVERFLOW': 'Hidden', 'Margin': 0, 'Padding': 0, 'Opacity': 0, // Make Sure Browse Button Is in The Right Side // In Internet Explorer 'DIRECTION ':' LTR ', // Max Zindex Supported by Opera 9.0-9.2' Zindex ': 2147483583}; // Make Sure That Element Opacity EXISTS. // OtherWise Use IE Filter IF (p.Style.opacity! == "0") {IF (TypeOf (P.Filters) == 'undefined') {throw new error ('Opacity Not Supported by the Browser');} P.Style.Filter = "Alpha (Opacity = 0)"; AddEvent (INPUT, 'CHANGE', FUNCTION () {if (! INPUT || INPUT.VALUE === ') {Return;} // get filename from input, required // as some Browsers Have Path Instead of IT Var file = filefromPath (Input.Value); if (false === Self._settings.onchange.call (self)) {self._clearinput (); return;} // Submit Form When Value Is changingIF (self._settings.autosubmit) {self.submit ();}}); addevent (Input, 'mouseover', function () {addclass (self._button, self._settings.hoverclass);}; addevent (Input , 'mouseout', function () {removeClass (self._button, self._settings.hoverClass); // We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input does not change If IT // Has Display None WHEN User Selects a file input.parentNode.style.visibility = 'hidden';}; p.Appendchild (Input); Document.body.Appendchild (p); this._input = input; _clearinput: function () {if (! this._input) {return;} // this._input.value = '; doesn't Work in IE6 RemoveNode (this._input.parentNode); this._input = null; this._createInput (); removeClass (this._button, this._settings.hoverClass);}, / ** * Function makes sure that when user clicks upload button, * the this. _INPUT IS CLICKED INSTEAD * / _ROUTECLICKS: Function () {var self = this; // ie will later display 'access Denied' error // if you use using self._input.click () // Other browsers just ignore click () AddEvent (self._button, 'mouseover', function () {i (self._disabled) {return;} f (! "{(!) {self._createInput ();} var P = self._input.parentNode; CopyLayout Self._button, p); p.style.visibility = 'visible';}); // commented Becausele We now hide input on mouseeleave / *** When the window is resized the elements * can be misaligned if button position depends * on window size * / // addResizeEvent (function () {// if (self._input) {// copyLayout (self._button, self._input .parentNode); //} //});}, / ** * createness iframe with unique name * @return {element} iframe * / _createiframe: function () {// We can't use gettime, Because IT Sometimes Return // Same Value in Safari :( var ID = getuid (); // we can set // Won't be the name attribute // Won't be protly registered in IE6, and new window // on form submit Will Open // var iFrame = Document.createElement ('iframe'); // iframe.setttribute ('name', id); var iframe = tolement (''); // src = "javascript: false; was added // because it possibly removes ie6 prompt // "This page contains both secure and nonsecure items" // Anyway, it does not do any harm iframe.setAttribute ( 'id', id); iframe. .style.display = 'none'; document.body.appendChild (iframe); return iframe;}, / ** * Creates form, that will be submitted to iframe * @param {Element} iframe Where to submit * @return { Element} form * / _createform: function (iframe) {var settings = this._settings; // We can't use the following code in IE6 // var form = document.createElement ('form'); // form.setttribute ('Method', 'POST'); // Form.SetaTRibute ('EncType', 'Multipart / Form-Data'); // Because In this case file won't be attached to requestVar form = TOELEMENT (' '); Form.Setattribute ('Action', Settings.Action); Form.SetAttribute ('Target', IFRAME.NAME); Form.Style.Display = 'None' Document.body.Appendchild (Form); // Create Hidden Input Element for Each Data Key for (VAR PROP IN Settings.Data) {IF (Settings.Data.hasownProperty (Prop) {var = Document.createElement (" INPUT "); el.setttribute ('Name', PROP); El.setttribute ('value', settings.data [prop]); Form.AppendChild (EL) ;}} return form;}, / ** * Gets response from iframe and fires onComplete event when ready * @param iframe * @param file Filename to use in onComplete callback * / _getResponse: function (iframe, file) {// geTTING RESPONSE VAR TODELETEFLAG = false, self = this, settings = this._settings; addevent (iframe, 'loading ", function () {ix (// for safari iframe.src ==" javascript:'% 3chtml% 3E% 3C / html% 3e '; "|| // for ff, ie iframe.src ==" JavaScript:' '; ") {//first time around, do not delete. // We reload to Blank Page, So That Reloading Main Page // Does Not Re-Submit The Post. if (Todeleteflag) {// FiX Busy State In ff3 setTimeout (IFRAME);}, 0);} return;} VAR DOC = iframe.contentdocument? iframe.ContentDocument: Window.frames [iframes [iframes.id] .document; // fixing Opera 9.26, 10.00 if (Doc.ReadyState && Doc.ReadyState! = 'Complete') {// Opera Fires Load Event Multiple Times // Even 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 Internet Explorer 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 SENTas 'application / javascript' or // 'text / javascript', then the browser wraps the text in a
 // 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;} f ("+" + ")");} else {response = {};}}} else};}}} else}; Is A XML Document Response = DOC;} settings.oncomplete.call (self, file, response); // ReloadBlank 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: '  '; ";});}, / ** * UPLOAD FILE Contained in this._input * / submit: function () {var self = this, settings = this._settings; if (! This._input || THIS ._INput.value === ') {return;} var file = filefromPath (this._input.value); // user returned false to cancel upload if (false === settings.onusubmit.call (this, file, getExt (file))) {this._clearinput (); return;} // sending request var iframe = this._createiframe (); var form = this._createform (iframe); // Assuming Following STRUCTURE / / P -> INPUT TYPE = 'file' Removenode (this._button, self._settings.hoverclass); form.Appendchild (this._input); form.submit (); / / request set, clean up removeNode (form); form = null; removeNode (this._input); this._input = null; // Get response from iframe and fire onComplete event when ready this._getResponse (iframe, file); / / GET Ready for Next Request this._createInput ();}};}) ();  
Thank you can read this article carefully, I hope Xiaobian share AjaxUPload.js Realization of file upload content helps everyone, and also hope that everyone will support Tumi clouds, pay attention to Tumi Cloud Industry Information Channel, find TUMI clouds, detailed solutions waiting for you!

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment