Upload in Ajax Mode

Source: Internet
Author: User
As shown in the question, how hard is it to implement file upload in an Ajax mode? This is not a question. It is a rhetorical question.

Here I declare that I should not consider Ajax as xhttprequest. Ajax also includes frame-based operations, right! I am talking about the ancient frame.

Xhttprequest does not support file upload. Therefore, we have to return to frame, especially IFRAME, for file upload.

Required materials:

1. You have basic JavaScript skills.
2. a hidden form and IFRAME. Here I name them uploadform and uploadresponse respectively.
3. a page for receiving files is called uploadimage. aspx.
4. A page for displaying files is called file. aspx.

Basic Principles:

Copy the HTML element of input type = file in the current form (form1) to another form (uploadform) dedicated to file upload, the target of uploadform points to the name of a hidden IFRAME (uploadresponse) framework. in this way, when the uploadform submit () operation is executed, the content of uploadform will be post to uploadimage through uploadresponse. execute the ASPX page. Because the IFRAME element uploadresponse and form Element uploadform are all in a hidden Div element, visitors will not see anything redundant from start to end.

Instance:

Default. aspx page.

<SCRIPT type = "text/JavaScript">

Function uploadimage (){
Var file = Document. getelementbyid ("imagefile ");
VaR uploadformelement = Document. getelementbyid ("uploadform ");

// Display the progress bar
Document. getelementbyid ("processdiv"). style. Display = "Block"; // The Progress Div

// Copy image data
Uploadformelement. removechild (uploadformelement. imagefile );
Uploadformelement. appendchild (File );
Document. getelementbyid ("uploadimagediv"). innerhtml = '<input type = "file" id = "imagefile" name = "imagefile"/> ';

// Submit image data
Uploadformelement. Submit ();
}

Function uploadimageresponse (response ){
Document. getelementbyid ("processdiv"). style. Display = "NONE"; // hide progresss Div
VaR errlabel = Document. getelementbyid ("uploadmessage ");
Errlabel. innerhtml = "";
Window. eval ("Var K =" + response );
If (K. Status = 1)
Errlabel. innerhtml = K. message;
Else if (K. Status = 2)
Errlabel. innerhtml = K. message;
Else
Eval ("tinymce. activeeditor. dom. add (tinymce. activeeditor. getbody (), 'img ', {SRC:' "+ K. message + "', style: 'border: 0px;'}, null );");

}

Function uploadbutton_onclick (){

}

</SCRIPT>

<Form ID = "form1" runat = "server">
<Div>
<! -- Gets replaced with tinymce, remember HTML in a textarea shocould be encoded -->
<Tinymce: textarea id = "elm1" theme = "advanced" plugins = "spellchecker, Safari, pagebreak, style, layer, table, save, advhr, advimage, advlink, emotions, iespell, inlinepopups, insertdatetime, preview, media, searchreplace, print, contextmenu, paste, directionality, fullscreen, noneditable, visualchars, nonbreaking, xhtmlxtras, template"
Theme_advanced_buttons1 = "bold, italic, underline, strikethrough, |, justifyleft, justifycenter, justifyright, justifyfull, |, fontselect, fontsizeselect, forecolor, backcolor, image"
Theme_advanced_buttons2 = "" theme_advanced_buttons3 = "" theme_advanced_buttons4 = ""
Theme_advanced_toolbar_location = "TOP" theme_advanced_toolbar_align = "Left" theme_advanced_path_location = "bottom"
Theme_advanced_resizing = "true" runat = "server"/>
<Div style = "margin-top: 5px">
Upload images:
<Br/>
<Div id = "uploadimagediv">
<Input type = "file" id = "imagefile" name = "imagefile"/> </div>
<Input type = "button" id = "uploadbutton" onclick = "uploadimage ();" value = "Upload"/>
<Span id = "uploadmessage" style = "border: 1px solid # cccccc; color: red;"> </span>
</Div>
<Div id = "processdiv" style = "display: none; color: #660066; font-family: Arial;">

Uploading images <span id = "FILENAME"/>
</Div>
</Div>
</Form>
<Div style = "display: none;">
<IFRAME name = "uploadresponse"> </iframe>
<Form ID = "uploadform" Action = "uploadimage. aspx? T = <% = datetime. Now. ticks %> "target =" uploadresponse"
Method = "Post" enctype = "multipart/form-Data">
<Input type = "file" name = "imagefile" value = ""/>
</Form>
</Div>

As shown above, first select the file to be uploaded, and then call the uploadimage function when you click the upload button (Name: uploadbutton, this function is used to copy the imagefile element of form1 input type = file to uploadform, replace the outerhtml of the original imagefile (because JavaScript does not support modifying the Value Attribute of the input type = file element ), of course, there is also a cute upload progress bar (which looks professional and cool ).

Function uploadimage (){
Var file = Document. getelementbyid ("imagefile ");
VaR uploadformelement = Document. getelementbyid ("uploadform ");

// Display the progress bar
Document. getelementbyid ("processdiv"). style. Display = "Block"; // The Progress Div

// Copy image data
Uploadformelement. removechild (uploadformelement. imagefile );
Uploadformelement. appendchild (File );
Document. getelementbyid ("uploadimagediv"). innerhtml = '<input type = "file" id = "imagefile" name = "imagefile"/> ';

// Submit image data
Uploadformelement. Submit ();
}

When the user clicks the upload button, the job is switched from uploadimage. aspxProgramTake over.

Protected void page_load (Object sender, eventargs E)
{
Page. response. cache. setcacheability (httpcacheability. nocache );

Int status = 0; // status
String message = ""; // feedback

// Check the file
If (request. Files. Count = 0)
{
Status = 1;
Message = "select the file to upload ";
Renderuploadscript (status, message );
}
String ext = path. getextension (request. Files [0]. filename). tolower ();
If (EXT! = ". Jpg" & ext! = ". Jpeg ")
{
Status = 2;
Message = "sorry, only JPG images are supported currently ";
Renderuploadscript (status, message );
}

Guid fileid = guid. newguid ();
String filename = server. mappath (string. Format ("~ \ Files \ Program 02.16.jpg ", fileid ));
Request. Files [0]. saveas (filename );
// Record to the current page

Renderuploadscript (0, String. Format ("file. aspx? Key = {0} ", fileid ));
}

Private void renderuploadscript (INT status, string mess)
{
String script = string. format ("<script language = 'javascript '> window. parent. uploadimageresponse ("{status: {0}, message: '{1}'}"); </SCRIPT> ", status, Mess );
Response. Write (SCRIPT );
Response. End ();
}

Through the httpwebrequest object, we can obtain any data from the client post or get to the server, uploadimage. the work of the ASPX page is very simple. It is only responsible for receiving post files and saving them to the specified location (for demonstration, I only use saveas ).

In addition, it should be noted that because the file is uploaded in Ajax mode, it means that your program will report system problems through JavaScript, here, I use a parameter named status to return the problem. If the value is 0, everything is normal. If the value is 0, the user does not provide the file, 2. the specified file type is not uploaded.

When the user uploads a file without any problems, the system saves the file and returns the state 0, attaches the display path of the file, and other State affiliated information is an error message.

Now return to default. aspx to see how to receive uploadimage. the information returned by aspx should be taken into account in uploadimage. aspx is a page and belongs to the uploadresponse element of IFRAME. Therefore, the method of accessing the window object or function of uploadresponse is as follows:

"<Script language = 'javascript '> window. Parent. uploadimageresponse (" {status: 0, message: 'file. aspx? Key = guid '} "); <SCRIPT>"

The default response script is as follows:

Function uploadimageresponse (response ){
Document. getelementbyid ("processdiv"). style. Display = "NONE"; // hide progresss Div
VaR errlabel = Document. getelementbyid ("uploadmessage ");
Errlabel. innerhtml = "";
Window. eval ("Var K =" + response );
If (K. Status = 1)
Errlabel. innerhtml = K. message;
Else if (K. Status = 2)
Errlabel. innerhtml = K. message;
Else
Eval ("tinymce. activeeditor. dom. add (tinymce. activeeditor. getbody (), 'img ', {SRC:' "+ K. message + "', style: 'border: 0px;'}, null );");

}

Only Insert the information contained in the message in the corresponding HTM editor.

OK !! We have solved all the major difficulties. The following shows how to see the file we uploaded. If the file cannot be seen in real time, it makes no sense to upload the Ajax file.

File. ASPX page FunctionCodeAs follows:

Protected void page_load (Object sender, eventargs E)
{

Guid key = new GUID (request. querystring ["key"]);

// Path of the image
String filename = server. mappath (string. Format ("~ /Files/program 02.16.jpg ", key ));
// Send the file
Response. contenttype = "image/JPEG ";
Response. writefile (filename, true );
Response. addfiledependency (filename );
Response. cache. setcacheability (httpcacheability. Public );
Response. cache. setallowresponseinbrowserhistory (true );
}

OK! Everything is done.

Demo program:

Http://files.cnblogs.com/csharpsharper/CoolThingsShow.rar

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.