Create an Ajax-Style File Upload

Source: Internet
Author: User

This article is translated. I forgot the original article. Google should find it.

 

Create an Ajax-Style File Upload

If you visit the ASP. NET Ajax forum, you will find that hundreds of people ask that when you put the file control in updatepanel, it cannot produce Ajax upload results. This certainly cannot produce Ajax results, because the XMLHTTPRequest object does not support this function when uploading data internally. In this article, I will show you how to upload files with Ajax effect. The tip is simple. I will use the IFRAME framework to upload files, so that the page will not be refreshed, And the progress will be roughly displayed during the page upload process. below is the running

 

The following describes the execution process in detail. Start from the main page.

 

<Fieldset>

<Legend> photo upload demo </legend>

<Div id = "divframe">

<IFRAME id = "ifrphoto" onLoad = "initphotoupload ()" scrolling = "no" frameborder = "0" hidefocus = "true" style = "text-align: center; vertical-align: middle; border-style: none; margin: 0px; width: 100%; Height: 55px "src =" photoupload. aspx "> </iframe>

</Div>

<Div id = "divuploadmessage" style = "padding-top: 4px; display: none"> </div>

<Div id = "divuploadprogress" style = "padding-top: 4px; display: none">

<Span style = "font-size: smaller"> Uploading photo... </span>

<Div>

<Table border = "0" cellpadding = "0" cellspacing = "2" style = "width: 100%">

<Tbody>

<Tr>

<TD id = "tdprogress1"> & nbsp; </TD>

<TD id = "tdprogress2"> & nbsp; </TD>

<TD id = "tdprogress3"> & nbsp; </TD>

<TD id = "tdprogress4"> & nbsp; </TD>

<TD id = "tdprogress5"> & nbsp; </TD>

<TD id = "tdprogress6"> & nbsp; </TD>

<TD id = "tdprogress7"> & nbsp; </TD>

<TD id = "tdprogress8"> & nbsp; </TD>

<TD id = "tdprogress9"> & nbsp; </TD>

<TD id = "tdprogress10"> & nbsp; </TD>

</Tr>

</Tbody>

</Table>

</Div>

</Div>

</Fieldset>

 

 

As you can see, I used some divs to display or hide the information and progress of the upload page, and most importantly, I bound the initphotoupload Method to the onload event of IFRAME, the following describes the content of the IFRAME page.

 

<Form ID = "photoupload" enctype = "multipart/form-Data" runat = "server">

<Div>

<Input id = "filphoto" type = "file" runat = "server"/>

</Div>

<Div id = "divupload" style = "padding-top: 4px">

<Input id = "btnupload" type = "button" value = "Upload photo"/>

</Div>

</Form> the IFRAME

 

 

The IFRAME page contains an upload control and a button submit button. Now let's take a look at how the initphotoupload function is executed.

Function initphotoupload ()

{

_ Divframe = Document. getelementbyid ('divframework ');

_ Divuploadmessage = Document. getelementbyid ('diduploadmessage ');

_ Divuploadprogress = Document. getelementbyid ('divuploadprogress ');

_ Ifrphoto = Document. getelementbyid ('ifrphoto ');

 

VaR btnupload = _ifrphoto.content+doc ument. getelementbyid ('btnupload ');

 

Btnupload. onclick = function (Event)

{

VaR filphoto = _ifrphoto.contentwindodoc ument. getelementbyid ('filphoto ');

 

// Baisic validation for photo

_ Divuploadmessage. style. Display = 'none ';

 

If (filphoto. value. Length = 0)

{

_ Divuploadmessage. innerhtml = '<span style = \ "color: # ff0000 \"> Please specify the file. </span> ';

_ Divuploadmessage. style. Display = '';

Filphoto. Focus ();

Return;

}

 

VaR Regexp =/^ ([A-Za-Z] :) | (\\{ 2} \ W +) \$ ?) (\ W [\ W]. * ))(.jpg |. jpg |. gif |. gif |. PNG |. PNG |. BMP |. BMP) $ /;

 

If (! Regexp. Test (filphoto. Value) // somehow the expression does not work in opera

{

_ Divuploadmessage. innerhtml = '<span style = \ "color: # ff0000 \"> invalid file type. Only supports JPG, GIF, PNG and BMP. </span> ';

_ Divuploadmessage. style. Display = '';

Filphoto. Focus ();

Return;

}

 

Beginphotouploadprogress ();

_Ifrphoto.content1_doc ument. getelementbyid ('photoupload'). Submit ();

_ Divframe. style. Display = 'none ';

}

}

 

Once the IFRAME framework is loaded, we execute some variables that use the _ prefix as the DOM element. We also added a reference to the button submission event in IFRAME. In the click event, first verify whether the uploaded file is empty. We also verify the image type. After these verification passes, we will call the beginphotouploadprogress method to process the uploaded file. The following is the beginphotouploadprogress process.

 

Function beginphotouploadprogress ()

{

_ Divuploadprogress. style. Display = '';

Clearphotouploadprogress ();

_ Photouploadprogresstout = setTimeout (updatephotouploadprogress, progress_interval );

}

 

Function clearphotouploadprogress ()

{

For (VAR I = 1; I <= _ maxloop; I ++)

{

Document. getelementbyid ('tdprogress' + I). style. backgroundcolor = 'transparent ';

}

 

Document. getelementbyid ('tdprogress1'). style. backgroundcolor = progress_color;

_ Loopcounter = 1;

}

 

Function updatephotouploadprogress ()

{

_ Loopcounter + = 1;

 

If (_ loopcounter <= _ maxloop)

{

Document. getelementbyid ('tdprogress' + _ loopcounter). style. backgroundcolor = progress_color;

}

Else

{

Clearphotouploadprogress ();

}

 

If (_ photouploadprogresstimer)

{

Cleartimeout (_ photouploadprogresstout );

}

 

_ Photouploadprogresstout = setTimeout (updatephotouploadprogress, progress_interval );

}

 

 

As you may have seen, our basic idea is to use timer (window. setTimeout) to display the upload progress. Download and check the server code.

 

Private const string script_template = "<" + "script" + "type = \" text/JavaScript \ "> window. parent. photouploadcomplete ('{0}', {1}); "+" <"+"/script "+"> ";

 

Private void page_load (Object sender, eventargs E)

{

If (ispostback)

{

// Sleeping for 10 seconds, fake delay, you shoshould not it try at home.

System. Threading. thread. Sleep (10*1000 );

Uploadphoto ();

}

}

 

Private void uploadphoto ()

{

String script = string. empty;

 

If (filphoto. postedfile! = NULL) & (filphoto. postedfile. contentlength> 0 ))

{

If (! Isvalidimagefile (filphoto ))

{

Script = string. Format (script_template, "the uploaded file is not a valid image file.", "true ");

}

}

Else

{

Script = string. Format (script_template, "Please specify a valid file.", "true ");

}

 

If (string. isnullorempty (SCRIPT ))

{

// Uploaded file is valid, now we can do whatever we like to do, copying it file system,

// Saving it in dB etc.

 

// Your logic goes here

 

Script = string. Format (script_template, "photo uploaded.", "false ");

}

 

// Now inject the script which will fire when the page is refreshed.

Clientscript. registerstartupscript (this. GetType (), "uploadpolicy", script );

}

 

Private Static bool isvalidimagefile (htmlinputfile file)

{

Try

{

Using (bitmap BMP = new Bitmap (file. postedfile. inputstream ))

{

Return true;

}

}

Catch (argumentexception)

{

// Throws exception if not valid image

}

 

Return false;

}

 

 

 

On the server, we also performed some basic verification. In addition, we also generated some scripts on the client that will call the photouploadcomplete function on the main page, it is used to show whether the upload is successful or failed.

The following is the photouploadcomplete code.

Function photouploadcomplete (message, iserror)

{

Clearphotouploadprogress ();

 

If (_ photouploadprogresstimer)

{

Cleartimeout (_ photouploadprogresstout );

}

 

_ Divuploadprogress. style. Display = 'none ';

_ Divuploadmessage. style. Display = 'none ';

_ Divframe. style. Display = '';

 

If (message. length)

{

VaR color = (iserror )? '# Ff000000':' #008000 ';

 

_ Divuploadmessage. innerhtml = '<span style = \ "color:' + color + '\; font-weight: bold">' + message + '</span> ';

_ Divuploadmessage. style. Display = '';

 

If (iserror)

{

_Ifrphoto.content1_doc ument. getelementbyid ('filphoto'). Focus ();

}

}

}

 

This function is very simple. For more information, see the source code.

 

Http://www.cnblogs.com/mqingqing123/archive/2007/08/03/842352.html

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.