Introduction
This article explains how to show a progress bar, without using any built-in control, while uploading a file to the server in an ASP.NET Web Application.
Using the code
In this code, we have used the JavaScript functions setInterval() and clearTimout() to show the progress bar. This will run the timer which increases the width of the DIV with a Grey background color. For each timer tick, the div width increases, appearing look like a progress bar.
The layout is as follows:
<div id="divUpload" style="display:none">
<div style="width:300pt;;text-align:center;">Uploading...</div>
<div style="width:300pt;height:20px; border:solid 1pt gray">
<div id="divProgress" runat="server"
style="width: 1pt; height: 20px; background-color:Gray;display:none">
</div>
</div>
<div style="width:300pt;;text-align:center;">
<asp:Label ID="lblPercentage" runat="server"
Text="Label"></asp:Label></div>
</div>
In the above code, 'divProgress' has a Gray background color and shows the progress bar. Its width increases during every timer tick.
The JavaScript code is as follows:
<script language="javascript" type="text/javascript">
var size = 2;
var id= 0;
function ProgressBar()
{
if(document.getElementById('<%=FileUpload1.ClientID %>').value != "")
{
document.getElementById("divProgress").style.display = "block";
document.getElementById("divUpload").style.display = "block";
id = setInterval("progress()",20);
return true;
}
else
{
alert("Select a file to upload");
return false;
}
}
function progress()
{
size = size + 1;
if(size > 299)
{
clearTimeout(id);
}
document.getElementById("divProgress").style.width = size + "pt";
document.getElementById("<%=lblPercentage.ClientID %>").
firstChild.data = parseInt(size / 3) + "%";
}
</script>
In the above JavaScript code, you can see two functions which will be called when you click the Upload button and starts the progress bar.
Points of Interest
JavaScript does a very good job on the client-side which gives the web application a live and dynamic status.