asp.net Simple file upload system without refreshing

Source: Internet
Author: User
Tags extend file upload httpcontext

asp.net Simple file upload system without refreshing
<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> Easy No Refresh file upload system </title>
<script src= "Cjl.0.1.min.js" ></script>
<script>

var quickupload = function (file, options) {





This.file = $$ (file);





This._sending = false;//is uploading


This._timer = null;//Timer


This._iframe = Null;//iframe Object


This._form = Null;//form Object


This._inputs = {};//input Object


This._ffinish = null;//Complete Execution function





$$.extend (This, this._setoptions (options));


};


Quickupload._counter = 1;


Quickupload.prototype = {


Set default Properties


_setoptions:function (options) {


This.options = {//default value


Action: "",//Set action


timeout:0,//set timeout (in seconds)


Parameter: {},//Parameter object


Onready:function () {},//upload ready to execute


Onfinish:function () {},//execution when upload completes


Onstop:function () {},//execution when upload stops


Ontimeout:function () {}//upload timeout execution


};


Return $$.extend (this.options, Options | | {});


},


Uploading files


Upload:function () {


Stop last Upload


This.stop ();


No file returned


if (!this.file | |!this.file.value) return;


May modify related properties in Onready so put it in front.


This.onready ();


Setting up Iframe,form and form controls


This._setiframe ();


This._setform ();


This._setinput ();


Set timeout


if (This.timeout &gt; 0) {


This._timer = settimeout ($ $F. Bind (This._timeout, this), this.timeout * 1000);


}


Start uploading


This._form.submit ();


This._sending = true;


},


Set IFRAME


_setiframe:function () {


if (!this._iframe) {


Create an IFRAME


var iframename = "Quickupload_" + quickupload._counter++,


iframe = document.createelement ($ $B. ie? "&lt;iframe name=" "+ Iframename +" "&gt;": "iframe");


Iframe.name = Iframename;


Iframe.style.display = "None";


Record completion procedure for easy removal


var finish = This._ffinish = $ $F. Bind (This._finish, this);


Execute the completion program after the IFRAME finishes loading


if ($ $B. IE) {


Iframe.attachevent ("onload", finish);


} else {


Iframe.onload = $ $B. Opera? function () {this.onload = finish;}: Finish;


}


Insert Body


var body = document.body; Body.insertbefore (iframe, body.childnodes[0]);





This._iframe = iframe;


}


},


Set form


_setform:function () {


if (!this._form) {


var form = document.createelement (' form '), file = This.file;


Setting properties


$$.extend (Form, {


Target:this._iframe.name, Method: "Post", Encoding: "Multipart/form-data"


});


Set style


$ $D. SetStyle (Form, {


padding:0, margin:0, border:0,


BackgroundColor: "Transparent", display: "Inline"


});


Remove form before submitting


File.form &amp;&amp; $ $E. Addevent (File.form, "submit", $ $F. Bind (This.dispose, this));


Insert Form


File.parentNode.insertBefore (form, file). appendchild (file);





This._form = form;


}


Action may Modify


This._form.action = this.action;


},


Set input


_setinput:function () {


var form = this._form, oldinputs = this._inputs, newinputs = {}, name;


Set input


for (name in This.parameter) {


var input = Form[name];


if (!input) {


If there is no corresponding input, create a new


input = document.createelement ("input");


Input.name = name; Input.type = "hidden";


Form.appendchild (input);


}


Input.value = This.parameter[name];


Log Current input


Newinputs[name] = input;


Delete an existing record


Delete Oldinputs[name];


}


Remove useless input


for (name in oldinputs) {form.removechild (Oldinputs[name]);}


Save current input


This._inputs = newinputs;


},


Stop uploading


Stop:function () {


if (this._sending) {


This._sending = false;


Cleartimeout (This._timer);


Reset iframe


if ($ $B. Opera) {//opera by setting SRC There will be a problem


This._removeiframe ();


} else {


THIS._IFRAME.SRC = "";


}


This.onstop ();


}


},


Destruction procedures


Dispose:function () {


This._sending = false;


Cleartimeout (This._timer);


Clear IFRAME


if ($ $B. Firefox) {


SetTimeout ($ $F. Bind (This._removeiframe, this), 0);


} else {


This._removeiframe ();


}


Clear Form


This._removeform ();


Clear Dom Association


this._inputs = This._ffinish = This.file = null;


},


Clear IFRAME


_removeiframe:function () {


if (this._iframe) {


var iframe = This._iframe;


$ $B. ie? Iframe.detachevent ("onload", This._ffinish): (iframe.onload = null);


Document.body.removeChild (IFRAME); This._iframe = null;


}


},


Clear Form


_removeform:function () {


if (this._form) {


var form = this._form, parent = Form.parentnode;


if (parent) {


Parent.insertbefore (this.file, form); Parent.removechild (form);


}


This._form = This._inputs = null;


}


},


Timeout function


_timeout:function () {


if (this._sending) {this._sending = false; This.stop (); This.ontimeout ();}


},


Completion function


_finish:function () {


if (this._sending) {this._sending = false; This.onfinish (this._iframe);}


}


}

&lt;/script&gt;


&lt;/head&gt;


&lt;body&gt;


&lt;br&gt;


File Properties View:


&lt;input id= "Idfile" name= "file" type= "file"/&gt;


&lt;script&gt;


var file = $$ ("Idfile"), Fu = new Quickupload (file, {action: "File.ashx"});


File.onchange = function () {fu.upload ();}


&lt;/script&gt;


&lt;br&gt;


&lt;br&gt;


&lt;br&gt;


&lt;br&gt;


&lt;style&gt;


. Upload {width:600px;background: #fff; font-size:12px; border-collapse:collapse;}


. upload td,. Upload TH {padding:5px;border:1px solid #ebebeb;}


. Upload thead td {Background-color: #ebebeb;}


. upload th {text-align:center;}


. upload b {font-size:14px;}


. Upload tbody td{height:30px;


. Upload tfoot td{word-spacing:20px;


Upload A:link,. Upload a:visited,. Upload a:hover,. Upload a:active {color: #00F;}


&lt;/style&gt;


&lt;form action= "Files.ashx" method= "post" enctype= "Multipart/form-data" &gt;


&lt;table border= "0" class= "upload" &gt;


&lt;thead&gt;


&lt;tr&gt;


&LT;TD colspan= "4" &gt;&lt;b&gt; File upload &lt;/b&gt;&lt;/td&gt;


&lt;/tr&gt;


&lt;tr&gt;


&lt;th&gt; Select File &lt;/th&gt;


&lt;th width= "25%" &gt; Rename &lt;/th&gt;


&lt;th width= "15%" &gt; Operations &lt;/th&gt;


&lt;th width= "15%" &gt; Status &lt;/th&gt;


&lt;/tr&gt;


&lt;/thead&gt;


&lt;tbody id= "IDTable" &gt;


&lt;tr&gt;


&lt;td&gt;&lt;input name= "File" type= "file"/&gt;


&lt;span&gt;&lt;/span&gt;&lt;/td&gt;


&lt;td&gt;&lt;input size= "name=" "title" type= "text"/&gt;


&lt;span&gt;&lt;/span&gt;&lt;/td&gt;


&LT;TD align= "center" &gt;&lt;a href= "?" &gt; Reset &lt;/a&gt;&lt;/td&gt;


&LT;TD align= "Center" &gt;&lt;span&gt; Select File &lt;/span&gt;&lt;/td&gt;


&lt;/tr&gt;


&lt;/tbody&gt;


&lt;tfoot&gt;


&lt;tr&gt;


&LT;TD colspan= "4" align= "Center" &gt;&lt;script&gt;


Document.writeln ("&lt;input id=" Idadd "type=" button "value=" Add File "&gt;")


Document.writeln ("&lt;input id=" Idquick "type=" button "value=" Speed Upload "&gt;")


&lt;/script&gt;


&lt;input id= "Idnormal" type= "Submit" value= "General upload" &gt;&lt;/td&gt;


&lt;/tr&gt;


&lt;/tfoot&gt;


&lt;/table&gt;


&lt;/form&gt;


&lt;script&gt;

var qus = [], count = 0, table = $$ ("idtable"), model = Table.removechild (table.rows[0));

function Add () {


var row = Model.clonenode (true),


Inputs = Row.getelementsbytagname ("input"),


File = Inputs[0], title = Inputs[1],


spans = Row.getelementsbytagname ("span"),


Msgfile = Spans[0], Msgtitle = spans[1], msg = spans[2],


A = Row.getelementsbytagname ("a") [0],


qu = new Quickupload (file, {


Action: "Files.ashx",


Timeout:6,


Onready:function () {


count++;


Show ("Upload ...");


a.innerhtml = "Stop"; A.onclick = function () {qu.stop (); return false;};


Set up the form


This.parameter.title = Title.value;





File.style.display = Title.style.display = "None";


msgfile.innerhtml = File.value; msgtitle.innerhtml = Title.value;


},


Onfinish:function (IFRAME) {


try{//processing return information (requires background coordination)


var info = eval ("+ Iframe.contentWindow.document.body.innerHTML +"));


Show ("Upload complete");


}catch (e) {//Get data error


Show ("Upload failed"); Stop (); Return


}


count--; CHECKBTN ();


row.cells[0].innerhtml = "&lt;a href=" "+ Info.path +" "target= ' _blank ' &gt;" + info.name + "&lt;/a&gt;";


row.cells[1].innerhtml = Info.name;


a.innerhtml = "Download"; A.href = Info.path; A.onclick = null;


Destruction procedures


This.dispose ();


},


Onstop:function () {Show ("Stopped");


Ontimeout:function () {Show ("Upload timeout"); Stop ();}


});





A.onclick = Reset





function Stop () {


count--; CHECKBTN ();


a.innerhtml = "Reset"; A.onclick = reset;


File.style.display = msgfile.innerhtml =


Title.style.display = msgtitle.innerhtml = "";


}





function Reset () {Show ("Select File"); Resetfile (file); return false; }





Function Show (m) {msg.innerhtml = m;}





File.onchange = function () {Show (this.value?) "Ready to Upload": "Select File"); }


Qus.push (QU);


Table.appendchild (row);


}

Add ();
Add ();
Add ();

$$ ("Idadd"). onclick = function () {
Qus.length >= 6? Alert ("Don't be too greedy"): Add ();
}

$$ ("Idquick"). onclick = function () {
$ $A. Filter (Qus, function (qu) {qu.upload ();}); CHECKBTN ();
}

function checkbtn () {
$$ ("Idnormal"). Disabled = $$ ("Idquick"). Disabled =!! Count
}

function Resetfile (file) {
File.value = "";//ff Chrome Safari
if (File.value) {
if ($ $B. IE) {//ie
With (File.parentNode.insertBefore (document.createelement (' form '), file) {
AppendChild (file); Reset (); Removenode (FALSE);
}
else {//opera
File.type = "text"; File.type = "File";
}
}
}
</script>
</body>

asp.net file

<%@ WebHandler language= "C #" class= "File_webhandler" debug= "true"%>

Using System;
Using System.Web;
Using System.IO;

public class File_webhandler:ihttphandler


{


public void ProcessRequest (HttpContext context)


{


if (context. Request.Files.Count &gt; 0)


{


Httppostedfile file = context. Request.files[0];


if (file. ContentLength &gt; 0 | | !string. IsNullOrEmpty (file. FileName))


{


String _msg = "file attributes";


_msg + = "NN filename:" + path.getfilename (file. FileName)


+ "NN suffix name:" + path.getextension (file. FileName)


+ "nn file length:" + files. ContentLength + "byte"


+ "NN file type:" + files. ContentType;

Context. Response.Write ("<script>alert (' + _msg + ');</script>");
}
}
}

public bool IsReusable
{
Get
{
return false;
}
}
}
Files.ashx file

<%@ WebHandler language= "C #" class= "File_webhandler" debug= "true"%>

Using System;
Using System.Web;
Using System.IO;
Using System.Text.RegularExpressions;

public class File_webhandler:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
httpfilecollection files = context. Request.Files;
if (Files. Count > 0)
{
String[] Titles = context. request.form["title"]. Split (', ');

for (int i = 0; i < files. Count; i++)
{
Httppostedfile file = Files[i];

if (file. ContentLength &gt; 0)


{


string title = Titles[i]. Trim ();


if (string. IsNullOrEmpty (title))


{


title = Path.getfilename (file. FileName);


}


Else


{


title = Regex.Replace (title, @ "[/:*?"] &lt;&gt;|] "," "");


Title + path.getextension (file. FileName);


}





String path = "./file/" + title;


File. SaveAs (System.Web.HttpContext.Current.Server.MapPath (path));


Context. Response.Write ("{path:" "+ Path +" ", Name:" "+ title +" "}");


}


}


}


}

public bool IsReusable
{
Get
{
return false;
}
}
}
JS file

Eval (function (p,a,c,k,e,r) {e=function (c) {return (c&lt;62? ': E (parseint (C/62))) + ((c=c%62) &gt;35? String.fromCharCode (c+29): c.tostring)};if (' 0 '. Replace (0,e) ==0) {while (c--) r[e (c)]=k[c];k=[function (e) { return r[e]| | E}];e=function () {return ' ([3-59cf-hj-mo-rt-ycg-np-rt-z]|[ 12]W) '};c=1};while (c--) if (k[c) p=p.replace (new RegExp (' B ' +e (c) + ' B ', ' G '), k[c]); return p} (' 5 $$,$ $B, $ $A, $ $F, $ $D, $ $E , $ $S;(3 () {5 o,b,a,f,d,e,s;o=3 (ID) {4 "1L" ==1t ID? P.getelementbyid (ID): id};o.extend=3 (g,10) {h (5 Q R) {g[q]=10[q]}4 g};o.deepextend=3 (g,10) {h (5 Q R) {5 17=10[q];9 (G= ==17) continue;9 (1t 17=== "C") {G[q]=i.callee (g[q]| | {},17)}j{g[q]=17}}4 G}; B= (3 (k) {5 b={11:/11/.x (k) &amp;&amp;!/1u/.x (k), 1u:/1u/.x (k), 1m:/webkit/.x (k) &amp;&amp;!/1v/.x (k), 1n:/1n/.x (k), 1v :/1v/.x (K)};5 1i= ""; H (5 i R b) {9 (B[i]) {1i= "1M" ==i?) ": i;19}}b.18=1i&amp;&amp;1w (": "+1i+") [\/:] ([\d.] +) "). x (K) 1w.$1:" 0 "; b.ie=b.11;b.1o=b.11&amp;&amp;1y (b.18) ==6;b.ie7=b.11&amp;&amp;1y (b.18) ==7;b.1p=b.11&amp; &AMP;1Y (b.18) ==8;4 B}) (1z.navigator.useragent.tolowercase ()); A=3 () {5 L={isarray:3 (1Q) {4 OBJECT.1R.TOSTRING.L (1Q) = = "[C 1S]"},1a:3 (c,12,p) {9 (c.1a) {4 c.1a ()}j{5 m=c.1a;p=1t (p)? 0: (p&lt;0) 1j.1u (P) +m:1j.1v (p); H (;p &lt;m;p++) {9 (c[i]===12) 4 I}4-1}},1b:3 (c,12,p) {9 (c.1b) {4 c.1b ()}j{5 m=c.1a;p=1t (P) | | P&gt;=m-1? M-1:P&LT;0?1J.1U (P) +m:1j.1v (p); H (;p &gt;-1;p--) {9 (c[i]===12) 4 i}4-1}}};3 X (c,q) {9 (undefined===c.1a) {h (5 F R C) {9 (w===q (c[f],f,c)) 19}}j{h (5 i=0,m= c.1a;i&lt;m;i++) {9 (I R c) {9 (w===q (c[i],i,c)) 19}}}; X ({1w:3 (c,q,j) {X.L (j,c,3 () {q.y (j,i)})},map:3 (c,q,j) {5 l=[]; X.L (j,c,3 () {l.1x (Q.y (j,i))}); 4 L},1k:3 (c,q,j) {5 l=[]; X.L (j,c,3 (1Y) {q.y (j,i) &amp;&amp;l.1x (1Y)}); 4 L},every:3 (c,q,j) {5 l=1b; X.L (j,c,3 () {9 (!q.y (j,i)) {l=w;4 W}}); 4 L},some:3 (c,q,j) {5 l=w; X.L (j,c,3 () {9 (Q.y (j,i)) {l=1b;4 W}}); 4 l}},3 (1z,f) {l[f]=3 (c,q,j) {9 (c[f)) {4 c[f] (q,j)}j{4 1Z (C,q,j)}}); 4 L} (); F= (3 () {5 1c=1s.1r.1c;4{bind:3 (1l,j) {5 1m=1c. L (i,2); 4 3 () {4 1l. Y (j,1m.20 1c. L (I))}},bindaseventlistener:3 (1l,j) {5 1m=1c. L (i,2); 4 3 (g) {4 1l. Y (J,[E.1D (g)].20 (1m)}}}) ();D ={1n:3 (m) {5 13=m?m.21:p;4 13.22.23| | 13.24.23},1o:3 (M) {5 13=m?m.21:p;4 13.22.25| | 13.24.25},1c:3 (a,b) {4 (u.1c=a.26?3 (a,b) {4!! (a.26 (b) &amp;16)} : 3 (a,b) {4 a!=b&amp;&amp;a.1c (b)}) (A,b)},v:3 (m) {5 o=0,n=0,t=0,u=0;9 (!m.27| | b.1p) {5 n=m;while (n) {o+=n.offsetleft,n+=n.offsettop;n=n.offsetparent}; T=o+m.offsetwidth; U=n+m.offsetheight}j{5 v=m.27 (); o=t=u.1o (m); N=U=U.1N (m); o+=v.o; t+=v.t; N+=V.N; u+=v.u};4{"O": O, "n": N, "T": T, "U": U}},clientrect:3 (m) {5 v=u.v (m), 1d=u.1o (M), 1e=u.1n (m); U-=1e;4 V},28:3 (k) {4 (u.28=p.1p?3 (k) {4 p.1p.29 (k,2a)}:3 (k) {4 k.1q}) (k)},2b:3 (k,f) {4 (u.2b=p.1p?3 (k,f) {5 h=p.1p.29 (k) 2a) 4 F R h?h[f]:h.getpropertyvalue (f)}:3 (k,f) {5 h=k.1q;9 (f== "Z") {9/1f (z= (. *))/i.x (h.1k)) {5 z=parsefloat (1w.$1); 4 Z ? Z/2c:0}4 1};9 (f== "2d") {f= "2e"}5 l=h[f]| | H[S.1G (f)];9 (!/^-?d+ (px) $/i.x (L) &amp;&amp;/^-?d/.x (L)) {h=k.h,o=h.o,2g=k.1h.o;k.1h.o=k.1q.o;h.o=l| | 0;l=h.pixelleft+ "px" h.o=o;k.1h.o=2g}4 L}) (K,f)},setstyle:3 (1e,h,14) {9 (!1e.1a) {1e=[1e]}9 (1t h== "1L") {5 s=h;h={};h [S]=14}a.1w (1e,3 (k) {h (5 f R h) {5 14=h[f];9 (f== "Z" &amp;&amp;b.ie) {k. h.1k= (k.1q.1k| | ""). 2h (/1f ([^)]*)/, "") + "1F (z=" +14*2c+ ")"}j 9 (f== "2d") {k.h[b.ie?] 2e ': ' Cssfloat ']=14}j{k.h[s.1g (f)]=14}}}}; E= (3 () {5 1f,1g,15=1;9 (1z.2i) {1f=3 (r,t,y) {r.2i (t,y,w)};1g=3 (r,t,y) {R.removeeventlistener (t,y,w)}}j{1f=3 (r,t,y) {9 (!y.$$15) y.$$15=15++;9 (!R.V) r.v={};5 w=r.v[t];9 (! W) {w=r.v[t]={};9 (r["on" +t]) {w[0]=r[' on ' +t]}}w[y.$$15]=y;r[' on ' +t]=1r};1g=3 (r,t,y) {9 (r.v&amp;&amp;r.v[t]) { Delete R.v[t][y.$$15]}};3 1r () {5 1s=1b,g=1d (); 5 w=u.v[g.t]; H (5 i R W) {u.$$1r=w[i];9 (U.$$1R (g) ===w) {1s=w}}4 1s}}3 1d (g) {9 (g) 4 g;g=1z.g;g.pagex=g.clientx+d.1o (); g.pagey= G.CLIENTY+D.1N (); G.target=g.srcelement;g.1j=1j;g.1k=1k;switch (g.t) {2j "mouseout": g.2k=g.toelement;19;2j " MouseOver ": G.2k=g.fromelement;19};4 g};3 1J () {u.cancelbubble=1b};3 1K () {u.1s=w};4{" 1f ": 1f," 1g ": 1g," 1d ": 1d}}) (); S={1g:3 (s) {4 s.2h (/-([A-z])/ig,3 (all,2l) {4 2l.touppercase ()})}};9 (b.1o) {Try{p.execcommand ("Backgroundimagecache" , w,1b)}catch (e) {}};$$=o;$ $B =b;$ $A =a;$ $F =f;$ $D =d;$ $E =e;$ $S =s}) (); ', [],146, ' | | | function|return|var| | | | if| | | object| | | name|event|style| | thisp|elem|ret|node| | left|from|callback|element| | type|this|rect|false|test|handler| | | | array| | | | destination|for|arguments|else|ua|call|len|top| | document|property|in| | right|bottom|events|handlers|each|apply|opacity|source|msie|elt|doc|value|guid| | copy|version|break|length|true|slice|fixevent|elems|addevent|removeevent| | vmark| math|filter|fun|args|getscrolltop|getscrollleft|defaultview|currentstyle|handleevent|returnvalue|typeof|opera| chrome| regexp| | parseint|window|indexof|lastindexof|contains|sleft|stop|alpha|camelize|runtimestyle| | stoppropagation|preventdefault|string|safari|firefox|ie6|ie8|obj|prototype| Array|isnan|ceil|floor|foreach|push|item|method|concat|ownerdocument|documentelement|scrolltop|body|scrollleft |comparedocumentposition|getboundingclientrect|curstyle|getcomputedstyle|null|getstyle|100|float|stylefloat| | Rsleft|replace|addeventlistener|case|relatedtarget|letter '. Split (' | '), 0,{})

Related Article

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.