This article describes the jquery plug-in ajaxupload implementation file upload operation code. Share to everyone for your reference. Specifically as follows:
The screenshot of the running effect is as follows:
Figure 1 before the file is uploaded
Figure 2 After the file is uploaded
The specific code is as follows:
1. Create a page and write HTML
Upload Document:
<div class= "UploadFile" >
<span id= "Doc" ><input type= "text" disabled= "disabled"/></span >
<input type= "hidden" id= "Hidfilename"/> <input type= "
button" id= "Btnuploadfile" value= "Upload"/ >
<input type= "button" id= "Btndeletefile" value= "Delete"/>
Upload Picture:
<div class= "uploadimg" >
"<input" type= "hidden"
Id= "Hidimgname"/> <input type= "button" id= "btnuploadimg" value= "Upload"/> <input type=
"button" id= " Btndeleteimg "value=" delete "/>
</div>
2. Reference Ajaxupload.js File
<script src= "/js/common/ajaxupload.js" type= "Text/javascript" ></script>
3. Write JS Script
Window.onload = function () {init ();//Initialize}//Initialize function init () {//Initialize document upload var btnfile = Document.getel
Ementbyid ("Btnuploadfile");
var doc = document.getElementById ("Doc");
var hidfilename = document.getElementById ("Hidfilename");
document.getElementById ("Btndeletefile"). onclick = function () {Delfile (doc, hidfilename);
G_ajxuploadfile (Btnfile, Doc, hidfilename);
Initialize picture upload var btnimg = document.getElementById ("btnuploadimg");
var img = document.getElementById ("Imgshow");
var hidimgname = document.getElementById ("Hidimgname");
document.getElementById ("Btndeleteimg"). onclick = function () {delimg (img, hidimgname);
G_AJXUPLOADIMG (Btnimg, IMG, hidimgname);
var g_ajxtempdir = "/file/temp/";
Document upload function G_ajxuploadfile (btn, Doc, hidput, action) {var button = btn, interval; New Ajaxupload (button, {action: (action = NULL | | action = = undefined)? '/common/uploadhandler.ashx?filetype=file ': action), data: {}, Name: ' MyFile ', onsubmit:function (file, ext) {if (!) ( Ext &&/^ (rar|zip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx| rar| zip| Pdf| Pdfx| Txt| csv| xls| Xlsx| doc| DOCX) $/.test (EXT)) {alert ("The document you uploaded is not in the correct format, please choose again!")
");
return false;
}, Oncomplete:function (file, response) {flagvalue = response; if (Flagvalue = = "1") {alert ("The document you uploaded is not in the correct format, please choose again!")
"); else if (Flagvalue = = "2") {alert ("The document you uploaded is greater than 2M, please choose again!")
"); else if (Flagvalue = = "3") {alert ("Document upload failed!")
");
else {hidput.value = response;
Doc.innerhtml= "<a href= '" + g_ajxtempdir + response + "' target= ' _blank ' >" + response + "</a>";
}
}
});
//Picture upload function g_ajxuploadimg (btn, IMG, hidput) {var button = btn, interval;
New Ajaxupload (button, {action: '/common/uploadhandler.ashx?filetype=img ', data: {}, Name: ' MyFile ', Onsubmit:function (FILe, ext) {if (!) ( Ext &&/^ (jpg| Jpg|png| Png|gif| GIF) $/.test (EXT)) {alert ("The picture you uploaded is not in the correct format, please choose again!")
");
return false;
}, Oncomplete:function (file, response) {flagvalue = response; if (Flagvalue = = "1") {alert ("The image you uploaded is not in the correct format, please choose again!")
"); else if (Flagvalue = = "2") {alert ("You upload a picture larger than 200K, please choose again!")
"); else if (Flagvalue = = "3") {alert ("Picture upload failed!")
");
else {hidput.value = response;
IMG.SRC = G_ajxtempdir + response;
}
}
});
//Delete document function Delfile (doc, hidput) {hidput.value = "";
doc.innerhtml = "<input type=\" text\ "disabled=\" disabled\ "/>";
//Delete picture function Delimg (img, hidput) {hidput.value = "";
IMG.SRC = "/images/nophoto.gif"; }
4, creating an/COMMON/UPLOADHANDLER.ASHX handler
<%@ WebHandler language= "C #" class= "Uploadhandler"%> using System;
Using System.Web;
Using System.Text.RegularExpressions;
Using System.IO; public class Uploadhandler:ihttphandler {private String _filedir = ""; File directory///<summary>///processing upload file (1: Incorrect file format, 2: File size incorrect, 3: Upload failed, file name: Upload success)///</summary>///<param Name= ' context ' ></param> public void ProcessRequest (HttpContext context) {_filedir = context.
Server.MapPath (@ "/file/temp/");
try {string result = ' 3 '; String FileType = context. request.querystring["FileType"]; Gets the upload file type if (FileType = = "File") {result = UploadFile (context);//Document upload} else if ( FileType = = "img") {result = Uploadimg (context); Picture Upload} context.
Response.Write (Result); The catch {context. Response.Write ("3");//3 file upload failed}}///<summary>///document upload///</summary>
<param name= "Context" ></param>///<returns></returns> private string UploadFile (Http Context context) {int cout = context.
Request.Files.Count; if (cout > 0) {httppostedfile HPF = context.
Request.files[0]; if (HPF!= null) {string fileext = Path.getextension (HPF. FileName).
ToLower (); can only upload files, filter not uploaded file types string filefilt = ". rar|. zip|. Pdf|. Pdfx|. Txt|. csv|. xls|. Xlsx|. doc|.
Docx ... ";
if (Filefilt.indexof (Fileext) <=-1) {return "1"; //determine file size int length = HPF.
ContentLength;
if (length > 2097152) {return "2";
Random rd = new Random ();
DateTime nowtime = DateTime.Now; String newfilename = nowTime.Year.ToString () + nowTime.Month.ToString () + nowTime.Day.ToString () + NowTime.Hour.ToString () + nowTime.Minute.ToString () + Nowtime.seconD.tostring () + Rd. Next (1000, 1000000) + path.getextension (HPF.
FileName); if (!
Directory.Exists (_filedir)) {directory.createdirectory (_filedir);
String fileName = _filedir + newfilename; Hpf.
SaveAs (FileName);
return newfilename;
} return "3"; ///<summary>///picture upload///</summary>///<param name= "context" ></param>///&L T;returns></returns> private String Uploadimg (HttpContext context) {int cout = context.
Request.Files.Count; if (cout > 0) {httppostedfile HPF = context.
Request.files[0]; if (HPF!= null) {string fileext = Path.getextension (HPF. FileName).
ToLower (); can only upload files, filter not uploaded file types string filefilt = ". Gif|. Jpg|. php|. jsp|. Jpeg|.
Png| ... ";
if (Filefilt.indexof (Fileext) <=-1) {return "1";
}//Determine file size int length = HPF.
ContentLength;
if (length > 204800) {return "2";
Random rd = new Random ();
DateTime nowtime = DateTime.Now; String newfilename = nowTime.Year.ToString () + nowTime.Month.ToString () + nowTime.Day.ToString () + NowTime.Hour.ToString () + nowTime.Minute.ToString () + nowTime.Second.ToString () + Rd. Next (1000, 1000000) + path.getextension (HPF.
FileName); if (!
Directory.Exists (_filedir)) {directory.createdirectory (_filedir);
String fileName = _filedir + newfilename; Hpf.
SaveAs (FileName);
return newfilename;
} return "3";
#region IHttpHandler member public bool IsReusable {get {throw new NotImplementedException ();} } #endregion}
Appendix 1: Page CSS Styles
/* Upload file
/* uploadfile{margin-bottom:10px;}
/* Upload picture/*
uploadimg{}
uploadimg img{width:102px height:64px border:1px solid #CCCCCC display:block;
Attachment 2:ajaxupload.js File
/** * AJAX Upload (http://valums.com/ajax-upload/) * Copyright (c) Andris Valums * Licensed under the MIT license (http://valums.com/mit-license/) * 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, Reg
Exp:true, Newcap:true, immed:true */** * wrapper for FireBug ' s console.log/function log () { if (typeof (console)!= ' undefined ' && typeof (Console.log) = = ' function ') {Array.prototype.unshift.call (AR
Guments, ' [Ajax Upload] ';
Console.log (Array.prototype.join.call (arguments, ")");
}/** * Attaches event 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 '); }/** * Attaches resize event to a window, limiting * number of event fired.
Fires only when Encounteres * Delay of 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 Addresizeevent (FN) {var timeout;
addevent (window, ' Resize ', function () {if (timeout) {cleartimeout (timeout);
} timeout = settimeout (FN, 100);
}); }//Needs More testing, 'll be rewriten to 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.getboundingclientrect ();
var doc = el.ownerdocument;
var body = Doc.body; var docelem = doc.documentelement; For ie var clienttop = docelem.clienttop | | Body.clienttop | |
0; var clientleft = Docelem.clientleft | | Body.clientleft | |
0; In Internet Explorer 7 getboundingclientrect The 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;
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) {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 the top-l EFT relative to the body * @param {Element} el * @return {Object} Contains left, top, Right,bottom * * Fun
Ction 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};
/** * Helper that 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 (style
S.hasownproperty (name)) {El.style[name] = Styles[name]; }}/** * Function places an absolutely positioned * element in 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 ', Widt
H:from.offsetwidth + ' px ', height:from.offsetHeight + ' px '}; }/** * Creates and returns element from HTML chunk * Uses InnerHTML to create a element * *
var toelement = (function () {var div = document.createelement (' div ');
return function (HTML) {div.innerhtml = html;
var el = Div.firstchild;
Return Div.removechild (EL);
};
})();
/** * Function generates unique ID * @return Unique ID/var getuid = (Function () {var id = 0;
return function () {return ' valumsajaxupload ' + id++;
};
})(); /** * Get file name from Path * @param {String} file path to file * @return filename/function file
Frompath (file) {return File.replace (/.* (\/|\\)/, ""); /** * Get file extension lowercase * @param {String} file name * @return file extenstion/Fu Nction 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 A element you want convert to * up Load button.
Tested dimentions up to 500x500px * @param {Object} options check defaults below. * * window.
Ajaxupload = function (button, options) {this._settings = {//Location of the Server-side upload script Action: ' upload.php ',//File upload name: ' UserFile ',//Additional data to send data : {},//Submit file as soon as it ' s selected Autosubmit:true,//The type of data ' re ExPEC
Ting back to the server.
HTML and XML are detected automatically. Only useful if you are using JSON data as a response.
Set to ' json ' in ' the ' case. Responsetype:false,//class applied to button when mouse is hovered Hoverclass: ' hover ',//Class A Pplied to Button when the AU is disabled disabledclass: ' disabled ',//when user selects a file, useful with AUT
Osubmit disabled//can return False to cancel upload onchange:function (file, extension) {}, Callback to fire before file was uploaded//You can return False to cancel upload onsubmit:function (file, extension) {},//Fired when file upload is completed//warning!
Don't use "FALSE" STRING as A response!
Oncomplete:function (file, response) {}};
Merge the users options with we 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 if (typeof button = = "string") {if (/^#.*/.test (button)) {//If jQuery user passes #elementId Don
' t Break it button = Button.slice (1);
button = document.getElementById (button); } if (!button | | button.nodetype!== 1) {throw new Error ("Please make sure", you ' re passing a valid Elem
Ent "); } if (button.nodeName.toUpperCase () = = ' A ') {//Disable link addevent (button, ' click ', F
Unction (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 won ' t do anything this._disabled = false; If the button was disabledBefore refresh if would remain//disabled in FireFox, let ' s fix it this.enable ();
This._rerouteclicks ();
}; Assigning methods to our 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 the display to fix problem with Sa Fari 4//The problem is this value of input doesn ' t change if it//has display none when user sel
ECTs a file This._input.parentnode.style.visibility = ' hidden '; }, Enable:function () {removeclass (This._button, THIS._SETTINGS.DISABLEDCLASS);
This._button.removeattribute (' disabled ');
this._disabled = false; },/** * creates invisible file input * That'll hover above the button * <div><input typ
E= ' file '/></div> */_createinput:function () {var self = this;
var input = document.createelement ("input");
Input.setattribute (' type ', ' file ');
Input.setattribute (' name ', this._settings.name); Addstyles (input, {' position ': ' absolute ',//in Opera ' Browse ' button//are clickable and It is located in//the right side of the input ' right ': 0, ' margin ': 0, ' padding ': 0
, ' fontsize ': ' 480px ', ' cursor ': ' pointer '});
var div = document.createelement ("div"); Addstyles (Div, {' Display ': ' block ', ' position ': ' absolute ', ' overflow ': ' Hidden ', ' ma
Rgin ': 0, ' padding ': 0, ' Opacity ': 0,//Make sure browse button are in the right side/in Internet Explorer ' d
Irection ': ' ltr ',//max zindex supported by Opera 9.0-9.2 ' ZIndex ': 2147483583});
Make sure that element opacity exists. Otherwise use IE filter if (div.style.opacity!== "0") {if (typeof (div.filters) = = ' undefined ')
{throw new Error (' Opacity not supported by the browser ');
} Div.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, file, Getext (file)) {self._clearinput ());
Return }//Submitform when value is changed if (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 the ' Display to fix problem ' with Safari 4//The problem was that the value of ' input do ESN ' t change if it//has display none when user selects a file input.parentNode.style.visibility
= ' hidden ';
});
Div.appendchild (input);
Document.body.appendChild (DIV);
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
*/_rerouteclicks:function () {var self = this; IE would later display ' Access Denied ' ERROR//If your use using Self._input.click ()//other browsers jus T ignore click () addevent (Self._button, ' mouseover ', function () {if (self._disabled) {Retu
Rn
} if (!self._input) {self._createinput ();
var div = Self._input.parentnode;
Copylayout (Self._button, Div);
div.style.visibility = ' visible ';
});
Commented because we now hide input to mouseleave/** * When the windows is resized the elements
* Can is misaligned if button position depends * on window size *///addresizeevent (function () { // if (self._input) {//Copylayout (Self._button, Self._input.parentnode);
// }
//}); /** * creates 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 ' t use following code as the name attribute//won ' t is properly registered in IE6, and new window
On form submit would open//var iframe = document.createelement (' iframe ');
Iframe.setattribute (' name ', id);
var iframe = toelement (' <iframe src= "javascript:false;" name= "' + ID + '"/> '); Src= "JAVASCRIPT:FALSE;
is added//because it possibly removes IE6 prompt//"This page contains both secure and nonsecure items"
Anyway, it doesn ' t does any harm.
Iframe.setattribute (' ID ', id); Iframe.style.display = ' None ';
Document.body.appendChild (IFRAME);
return iframe; },/** * Creates form, that would be submitted to the 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.setattribute (' method ', ' post ');
Form.setattribute (' enctype ', ' multipart/form-data '); Because in the case file won ' t is attached to request var form = toelement (' <form method= ' post "en
Ctype= "Multipart/form-data" ></form> ");
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 el = document.createelement ("input");
El.setattribute (' type ', ' hidden ');
El.setattribute (' name ', prop);
El.setattribute (' value ', Settings.data[prop]);
Form.appendchild (EL);
} return form; },/** * Gets response from the IFRAME and fires OnComplete event when ready * @param iframe * @param f Ile Filename to use in OnComplete callback * * _getresponse:function (iframe, file) {//Getting respons
e var Todeleteflag = false, self = this, settings = this._settings; Addevent (IFRAME, ' Load ', function () {if (//for Safari IFRAME.SRC = = "javascript: '%3chtml%3e%3c/ht
ml%3e '; ' | | For FF, IE iframe.src = "javascript: ' <html></html> ';")
{///around, does not delete. We reload to blank page and so that reloading main pAge//Does not re-submit the post. if (Todeleteflag) {//Fix busy state in FF3 settimeout (function () {Removenode (
IFRAME);
}, 0);
} return; var doc = iframe.contentdocument?
Iframe.contentdocument:window.frames[iframe.id].document; Fixing opera 9.26,10.00 if (doc.readystate && doc.readystate!= ' complete ') {//Opera fire s Load event multiple times//Even when the DOM isn't not ready yet//This fix should not affect othe
R browsers return; }//Fixing opera 9.64 if (doc.body && Doc.body.innerHTML = = "false") {//in Opera 9.64 event is fired second time//then body.innerhtml changed from false//to server response a Pprox.
After the 1 SEC return;
} var response; If (Doc. XmlDocument) {//response is an 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 Do Cument is sent as ' application/javascript ' or//' text/javascript ', then the browser wraps the text in a ;p re>//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 Pro
Perty to retrieve the unmangled content. Note This IE6 only understands text/html if (Doc.body.firstChild && doc.body.firstchild.nodename.t
Ouppercase () = = ' PRE ') {response = Doc.body.firstChild.firstChild.nodeValue; } if (Response) {response = eval ("+ response +"));
else {response = {};
}} else {//response is a XML document response = doc;
} settings.onComplete.call (self, file, response); Reload blank page, so this 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> ';";
});
},/** * 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.onSubmit.call (this, file, getEXT (file)) {this._clearinput ();
Return
}//Sending request var iframe = This._createiframe ();
var form = This._createform (iframe);
Assuming following structure//div-> input type= ' file ' Removenode (This._input.parentnode);
Removeclass (Self._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 the IFRAME and fire OnComplete event when ready this._getresponse (iframe, file);
Get ready for Next request This._createinput ();
}
};
})();
Above is the ajaxupload implementation of file upload operation of the detailed code, I hope to help you learn.