Search content within the blog

Wednesday, May 6, 2009

Showing progress bar while uploading file in ASP.net

The following code uses javascript setinterval, clearTimeout to show an progress bar while uploading a file in asp.net.

The code is self explanatory....

ASPX Page code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 id="Head1" runat="server">
<title>Untitled Page</title>
<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()
{
//alert(id);
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>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:left">
<asp:FileUpload ID="FileUpload1" runat="server" /> <br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClientClick="return ProgressBar()" OnClick="Button1_Click" /><br /><br />
<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>
</div>
<br />
<asp:Label ID="Label1" runat="server" ForeColor="Red" Text=""></asp:Label>
</form>
</body>
</html>


ASPX.CS Code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
// Do code here to saving a file from fileupload control
//FileUpload1.PostedFile.SaveAs("path");
System.Threading.Thread.Sleep(8000);
Label1.Text = "Upload successfull!";
}
}

1 comment:

  1. Really its helpful.. I am searching for multiple file upload in ASP-C# with progress bar.. Pls do post if any..

    ReplyDelete