I,
You can use IFRAME to upload a non-refreshing file. In fact, it is refreshed, but it is hidden in IFRAME.
Simple principles:
<Form ID = "form1" method = "Post" Action = "Upload. Do" enctype = "multipart/form-Data" target = "uploadframe">
<Input type = "file" id = "Upload" name = "File Upload"/>
</Form>
<IFRAME id = "uploadframe" name = "result_frame" style = "visibility: hidden;"> </iframe>
The target in form must be equal to the ID value in IFRAME, indicating that the form has a post event, that is, when the post time is set, the IFRAME is refreshed instead of the entire page.
II,
The use of jquery plug-in ajaxfileupload can be simple implementation of this asynchronous upload effect plug-in address: http://www.phpletter.com/Our-Projects/AjaxFileUpload/
<SCRIPT type = "text/JavaScript" Language = "JavaScript" src = "JS/jquery. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" Language = "JavaScript" src = "JS/ajaxfileupload. js"> </SCRIPT>
Function ajaxfileupload ()
{
$ ("# Loading ")
. Ajaxstart (function (){
$ (This). Show ();
})
. Ajaxcomplete (function (){
$ (This). Hide ();
});
$. Ajaxfileupload
(
{
URL: 'upload. ashx ',
Secureuri: false,
Fileelementid: 'filetupload ',
Datatype: 'json ',
Success: function (data, status)
{
If (typeof (data. Error )! = 'Undefined ')
{
If (data. Error! = '')
{
Alert (data. Error );
} Else
{
Alert (data. msg );
}
}
},
Error: function (data, status, E)
{
Alert (E );
}
}
)
Return false;
}
<Input id = "filetoupload" type = "file" size = "45" name = "filetoupload">
<Input type = "button" id = "buttonupload" onclick = "Return ajaxfileupload ();">
Upload </input>
Upload. ashx
If (request. Files. Count> 0)
{
Httppostedfile file = request. Files [0];
String MSG = "";
String error = "";
If (file. contentlength = 0)
Error = "the file length is 0 ";
Else
{
File. saveas (server. mappath ("file") + "\" + path. getfilename (file. filename ));
MSG = "uploaded ";
}
String result = "{error: '" + error + "', MSG: '" + MSG + "'}";
Response. Write (result );
Response. End ();
}
PS: ajaxfileupload. JS Code
Jquery. Extend ({
Createuploadiframe: function (ID, Uri)
{
// Create Frame
VaR frameid = 'juploadframe '+ ID;
If (window. activexobject ){
VaR IO = Document. createelement ('<IFRAME id = "' + frameid + '" name = "' + frameid + '"/> ');
If (typeof uri = 'boolean '){
Io. src = 'javascript: false ';
}
Else if (typeof uri = 'string '){
Io. src = URI;
}
}
Else {
VaR IO = Document. createelement ('iframe ');
Io. ID = frameid;
Io. Name = frameid;
}
Io. style. Position = 'absolute ';
Io. style. Top = '-1000px ';
Io. style. Left = '-1000px ';
Document. Body. appendchild (IO );
Return Io
},
Createuploadform: function (ID, fileelementid)
{
// Create form
VaR formid = 'juploadform' + ID;
VaR fileid = 'juploadfile' + ID;
VaR form = $ ('<form action = "" method = "Post" name = "' + formid + '" id = "' + formid + '" enctype = "multipart/ form-Data "> </form> ');
VaR oldelement = $ ('#' + fileelementid );
VaR newelement = $ (oldelement). Clone ();
$ (Oldelement). ATTR ('id', fileid );
$ (Oldelement). Before (newelement );
$ (Oldelement). appendto (form );
// Set attributes
Parameters (form).css ('position', 'absolute ');
((Form).css ('top', '-margin px ');
Optional (form).css ('left', '-margin px ');
$ (Form). appendto ('body ');
Return form;
},
Ajaxfileupload: function (s ){
// Todo introduce global settings, allowing the client to modify them for all requests, not only timeout
S = jquery. Extend ({}, jquery. ajaxsettings, S );
VaR id = new date (). gettime ()
VaR form = jquery. createuploadform (ID, S. fileelementid );
VaR IO = jquery. createuploadiframe (ID, S. secureuri );
VaR frameid = 'juploadframe '+ ID;
VaR formid = 'juploadform' + ID;
// Watch for a new set of requests
If (S. Global &&! Jquery. Active ++)
{
Jquery. event. Trigger ("ajaxstart ");
}
VaR requestdone = false;
// Create the request object
VaR XML = {}
If (S. Global)
Jquery. event. Trigger ("ajaxsend", [XML, S]);
// Wait for a response to come back
VaR uploadcallback = function (istimeout)
{
VaR IO = Document. getelementbyid (frameid );
Try
{
If (Io. contentWindow)
{
XML. responsetext = io.contentdomaindoc ument. Body? Io.contentdomaindoc ument. Body. innerhtml: NULL;
XML. responsexml = io.content20.doc ument. xmldocument? Io.content+doc ument. xmldocument: io.content+doc ument;
} Else if (Io. contentdocument)
{
XML. responsetext = io.contentdocument.doc ument. Body? Io.contentdocument.doc ument. Body. innerhtml: NULL;
XML. responsexml = io.contentdocument.doc ument. xmldocument? Io.contentdocument.doc ument. xmldocument: io.contentdocument.doc ument;
}
} Catch (E)
{
Jquery. handleerror (S, XML, null, e );
}
If (XML | istimeout = "timeout ")
{
Requestdone = true;
VaR status;
Try {
Status = istimeout! = "Timeout "? "Success": "error ";
// Make sure that the request was successful or notmodified
If (status! = "Error ")
{
// Process the data (runs the XML through httpdata regardless of callback)
VaR DATA = jquery. uploadhttpdata (XML, S. datatype );
// If a local callback was specified, fire it and pass it the data
If (S. Success)
S. Success (data, status );
// Fire the global callback
If (S. Global)
Jquery. event. Trigger ("ajaxsuccess", [XML, S]);
} Else
Jquery. handleerror (S, XML, status );
} Catch (E)
{
Status = "error ";
Jquery. handleerror (S, XML, status, e );
}
// The request was completed
If (S. Global)
Jquery. event. Trigger ("ajaxcomplete", [XML, S]);
// Handle the global Ajax counter
If (S. Global &&! -- Jquery. Active)
Jquery. event. Trigger ("ajaxstop ");
// Process Result
If (S. Complete)
S. Complete (XML, status );
Jquery (IO). Unbind ()
SetTimeout (function ()
{Try
{
$ (IO). Remove ();
$ (Form). Remove ();
} Catch (E)
{
Jquery. handleerror (S, XML, null, e );
}
}, 100)
Xml = NULL
}
}
// Timeout checker
If (S. Timeout> 0)
{
SetTimeout (function (){
// Check to see if the request is still happening
If (! Requestdone) uploadcallback ("timeout ");
}, S. Timeout );
}
Try
{
// Var IO = $ ('#' + frameid );
VaR form = $ ('#' + formid );
$ (Form). ATTR ('action', S. url );
$ (Form). ATTR ('method', 'post ');
$ (Form). ATTR ('target', frameid );
If (Form. Encoding)
{
Form. Encoding = 'multipart/form-data ';
}
Else
{
Form. enctype = 'multipart/form-data ';
}
$ (Form). Submit ();
} Catch (E)
{
Jquery. handleerror (S, XML, null, e );
}
If (window. attachevent ){
Document. getelementbyid (frameid). attachevent ('onload', uploadcallback );
}
Else {
Document. getelementbyid (frameid). addeventlistener ('load', uploadcallback, false );
}
Return {ABORT: function (){}};
},
Uploadhttpdata: function (R, type ){
VaR DATA =! Type;
Data = type = "XML" | data? R. responsexml: R. responsetext;
// If the type is "script", Eval it in global context
If (type = "script ")
Jquery. globaleval (data );
// Get the JavaScript Object, if JSON is used.
If (type = "JSON ")
Eval ("Data =" + data );
// Evaluate scripts within HTML
If (type = "html ")
Jquery ("<div>" ).html (data). evalscripts ();
// Alert ($ ('param', data). Each (function () {alert ($ (this). ATTR ('value '));}));
Return data;
}
})
Iii. Upload with pure IFRAME
Upload. ashx
// <% @ Webhandler Language = "C #" class = "Upload" %>
Using system;
Using system. Web;
Public class upload: ihttphandler {
Private string JS (string v) {// This function is used to escape and replace Javascript. This prevents the string from being closed in JS output after 'is entered in the string.
If (V = NULL) Return "";
Return v. Replace ("'",@"\'");
}
// The following is a simple example: Save the uploaded file. If you want to verify the suffix of the uploaded file, you have to write it yourself and write the database or something.
Public void processrequest (httpcontext context ){
Httprequest request = context. request;
Httpresponse response = context. response;
Httpserverutility Server = context. server;
// Specify the output header and encoding
Response. contenttype = "text/html ";
Response. charset = "UTF-8 ";
Httppostedfile F = request. Files ["upfile"]; // obtain the uploaded file
String des = request. Form ["des"] // get the description
, Newfilename = guid. newguid (). tostring (); // use guid to generate a new file name.
If (F. filename = "") // file not uploaded
Response. Write ("<SCRIPT> parent. updatemsg ('', ''); </SCRIPT>"); // output Js. Use the parent object to get reference to the parent page.
Else {// save the file
Newfilename + = system. Io. Path. getextension (F. filename); // Add the extension
Try {
F. saveas (server. mappath ("~ /Uploads/"+ newfilename); // if you want to save it to another place, modify it here
// Call the parent process to update the content. Be sure to replace the des variable with JavaScript escape to prevent errors when the string is not closed.
Response. Write ("<SCRIPT> parent. updatemsg ('" + JS (DES) + "', '" + newfilename + "') </SCRIPT> ");
}
Catch {
Response. Write ("<SCRIPT> alert ('failed to save the file! \ N check whether the folder has write permission! '); </SCRIPT> "); // if the file fails to be saved, output a JS prompt indicating that the file failed to be saved.
}
}
}
Public bool isreusable {
Get {
Return false;
}
}
}
Test.htm
<!! 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> use a hidden IFRAME to implement Ajax refreshing upload </title>
</Head>
<Body>
<SCRIPT type = "text/JavaScript">
Function updatemsg (DES, filename) {// This function is used to provide JS callback to submitted pages, such as upload. ashx, to update information on the current page.
If (filename = '') {alert ('file not uploaded! '); Return false ;}
Document. getelementbyid ('ajaxmsg '). innerhtml =' the "file description" you entered in the form is: '+ des +' <br/>'
+ 'Uploaded image: <a href = "uploads/'+ filename +'" target = "_ blank"> '+ filename +' </a> ';
}
Function check (f ){
If (F. Des. value = ''){
Alert ('Enter the file description! '); F. Des. Focus (); Return false;
}
If (F. upfile. value = ''){
Alert ('select a file! '); F. upfile. Focus (); Return false;
}
}
</SCRIPT>
<! -- Hide IFRAME to accept the information submitted by the form -->
<IFRAME name = "ajaxifr" style = "display: none;"> </iframe>
<! -- Set target = "ajaxifr" here, so that the form is submitted to the IFRAME. If the target attribute is not set in peacetime, the form is submitted to the current page by default. -->
<! -- Note that when IFRAME is used, JS can be directly output to the submitted page to operate the parent page information. Generally, you need to return information when Ajax submits text information, if it is JS information, you still need to run eval -->
<Form method = "Post" enctype = "multipart/form-Data" Action = "Upload. ashx" target = "ajaxifr" onsubmit = "Return check (this)">
File Description: <input type = "text" name = "des"/> <br>
Select a file: <input type = "file" name = "upfile"/> <br>
<Input type = "Submit" value = "Submit"/>
</Form>
<! -- Put This Div to implement the upload result -->
<Div id = "ajaxmsg"> </div>
</Body>
</Html>