C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » ASP.NET WebForms »

Progress Bar for FileUploadControl - Asp.net


Posted Date: 08 Jun 2009    Resource Type: Code Snippets    Category: ASP.NET WebForms
Author: Gaurav AroraMember Level: Diamond    
Rating: 5 out of 55 out of 55 out of 55 out of 55 out of 5Points: 40



Progress Bar for FileUploadControl - Asp.net



Many times I have asked this question that How can I show a progress Bar with FileUloadControl in Asp.net?

Its a very easy and a tactic task. The logic behind this is just to get the total time take for upload a file into server. The following code-snippet describes the same:


Design File:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="fileUpload.aspx.cs" Inherits="fileUpload" %>

<!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 runat="server">
<style type="text/css">
html
{
background-color: Gray;
font: 14px Georgia,Serif,Garamond;
}
h1
{
color: Green;
font-size: 18px;
border-bottom: Solid 1px orange;
}
.clear
{
clear: both;
}
.lbl
{
color: green;
font-weight: bold;
}
.upperColumn
{
margin: auto;
width: 600px;
border-bottom: Solid 1px orange;
background-color: white;
padding: 10px;
}
.bottomColumn
{
margin: auto;
width: 600px;
background-color: white;
padding: 10px;
}
</style>
<title>File Upload</title>

<script language="javascript" type="text/javascript">
var size = 2;
var id= 0;

function ProgressBar()
{
if(document.getElementById('<%=ImageFile.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>

</head>
<body>
<form id="form1" runat="server">
<div class="upperColumn">
<h1>
File Upload Example</h1>
<asp:Label ID="lblImageFile" Text="Load Image" AssociatedControlID="ImageFile" runat="server"
CssClass="lbl" />
<asp:FileUpload ID="ImageFile" runat="server" />
<br />
<br />
<asp:Button ID="btnAddImage" runat="server" Text="Add Image" OnClientClick="return ProgressBar()"
OnClick="btnAddImage_Click" />
<asp:Button ID="btnShowImage" Text="Show Image" runat="server" OnClick="btnShowImage_Click" />
<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: orange;
display: none">
</div>
</div>
<div style="width: 300pt; text-align: center;">
<asp:Label ID="lblPercentage" runat="server" Text="Label"></asp:Label></div>
<br />
<asp:Label ID="Label1" runat="server" ForeColor="Red" Text=""></asp:Label>
</div>
</div>
<br class="clear" />
<div class="bottomColumn">
<asp:DataList ID="dlImageList" RepeatColumns="3" runat="server">
<ItemTemplate>
<asp:Image ID="imgShow" ImageUrl='<%# Eval("Name","~/UploadImages/{0}")%>' Style="width: 200px"
runat="server" AlternateText='<%# Eval("Name") %>' />
<br />
<%# Eval("Name") %>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>



Code-Behind File:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;

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

}
protected void btnAddImage_Click(object sender, EventArgs e)
{
if (ImageFile.HasFile) //if file uploaded
{
if (checkFileType(ImageFile.FileName)) //Check for file types
{
try
{
//save file
ImageFile.SaveAs(MapPath("~/UploadImages/" + ImageFile.FileName));
//Response.Write("<script language =Javascript> alert('File Uploaded Successfully, Click Show Images');</script>");
System.Threading.Thread.Sleep(8000);
Label1.Text = "Upload successfull!";
}
catch (System.IO.DirectoryNotFoundException)
{
createDir();
}
}
}
else
{
Response.Write("<script language =Javascript> alert('Invalid File Format, choose .gif,.png..jpg.jpeg');</script>");
}
}
private bool checkFileType(string fileName)
{
string fileExt = Path.GetExtension(ImageFile.FileName);

switch (fileExt.ToLower())
{
case ".gif":
return true;
case ".png":
return true;
case ".jpg":
return true;
case ".jpeg":
return true;
default:
return false;
}

}
private void createDir()
{
DirectoryInfo myDir = new DirectoryInfo(MapPath("~/UploadImages/"));
myDir.Create();

//Now save file
ImageFile.SaveAs(MapPath("~/UploadImages/" + ImageFile.FileName));
Response.Write("<script language =Javascript> alert('File Uploaded Successfully,Click Show Images');</script>");
}
protected void btnShowImage_Click(object sender, EventArgs e)
{
DirectoryInfo myDir = new DirectoryInfo(MapPath("~/UploadImages/"));
try
{

dlImageList.DataSource = myDir.GetFiles();
dlImageList.DataBind();

}
catch (System.IO.DirectoryNotFoundException)
{
Response.Write("<script language =Javascript> alert('Upload File(s) First!');</script>");
}
}

}



Code-Behind File-using VB.NET:


Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO

Public Partial Class fileUpload
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
Protected Sub btnAddImage_Click(ByVal sender As Object, ByVal e As EventArgs)
If ImageFile.HasFile Then
'if file uploaded
If checkFileType(ImageFile.FileName) Then
'Check for file types
Try
'save file
ImageFile.SaveAs(MapPath("~/UploadImages/" & ImageFile.FileName))
'Response.Write("<script language =Javascript> alert('File Uploaded Successfully, Click Show Images');");
System.Threading.Thread.Sleep(8000)
Label1.Text = "Upload successfull!"
Catch generatedExceptionName As System.IO.DirectoryNotFoundException
createDir()
End Try
End If
Else
Response.Write("<script language =Javascript> alert('Invalid File Format, choose .gif,.png..jpg.jpeg');</script>")
End If
End Sub
Private Function checkFileType(ByVal fileName As String) As Boolean
Dim fileExt As String = Path.GetExtension(ImageFile.FileName)

Select Case fileExt.ToLower()
Case ".gif"
Return True
Case ".png"
Return True
Case ".jpg"
Return True
Case ".jpeg"
Return True
Case Else
Return False

End Select
End Function
Private Sub createDir()
Dim myDir As New DirectoryInfo(MapPath("~/UploadImages/"))
myDir.Create()

'Now save file
ImageFile.SaveAs(MapPath("~/UploadImages/" & ImageFile.FileName))
Response.Write("<script language =Javascript> alert('File Uploaded Successfully,Click Show Images');")
End Sub
Protected Sub btnShowImage_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim myDir As New DirectoryInfo(MapPath("~/UploadImages/"))
Try

dlImageList.DataSource = myDir.GetFiles()

dlImageList.DataBind()
Catch generatedExceptionName As System.IO.DirectoryNotFoundException
Response.Write("<script language =Javascript> alert('Upload File(s) First!');")
End Try
End Sub

End Class


Try above code and you will get following output as shown in snapshots:
  • Initial stage of the running code/application

  • Select to upload an image file [I have developed a sample which excepts only Image files]

  • Uploading images with Progress in %age

  • Message, when upload completed

  • Clicking on 'ShowImage' button will display uploaded image(s)


    Note:
  • In above code, the actual time of uploading may be different
  • Progress in on the basis of 100-chunks
  • Please feel free to revert back for any further assistant.


    Attachments














  • Responses

    Author: VMRK    06 Jul 2009Member Level: Silver   Points : 1
    Its really a good one .Can you please add some screenshot to show how it works in IE


    Author: Gaurav Arora    09 Jul 2009Member Level: Diamond   Points : 1
    Rajkumar,

    Thanks for your words, I have uplaoded snapshots from IE6.0. Hope , you will be benefited.


    Author: satya    10 Jul 2009Member Level: Diamond   Points : 1
    The way you have formatted the resource easily understandable.

    I even want to post my resource in the same, how do I post it.

    Please suggest me......


    Author: Gaurav Arora    10 Jul 2009Member Level: Diamond   Points : 0
    Hi Satya,
    You can do it. What kind of help you want from me.


    Author: Miss Meetu Choudhary    11 Jul 2009Member Level: Diamond   Points : 1
    Hi Gaurav,
    Really nice and well formatted resource.. Keep it up.

    ++
    Thanks and Regards.
    Meetu Choudhary.
    Site Coordinator.


    Author: R.Jaya kumar (JK)    13 Jul 2009Member Level: Diamond   Points : 0
    Hi Gaurav,
    pl convert .aspx,.vb



    Author: Abhay    14 Aug 2009Member Level: Diamond   Points : 1
    Hi Gaurav,

    good one .

    keep it up.

    contribute more.

    Thanks and Regards
    Abhay


    Author: Gaurav Arora    22 Aug 2009Member Level: Diamond   Points : 0
    R. Jaya Kumar,

    Thanks for your suggestions, I supplied vb.net code too.


    Author: R.Jaya kumar (JK)    22 Aug 2009Member Level: Diamond   Points : 1
    Really Good one
    thanks Mr.Gaurav Arora
    again attach zip format then alert intimate intially so intimate populate using labels


    Feedbacks      
    Popular Tags   What are tags ?   Search Tags  
    Sign In to add tags.
    Progress Bar  .  Gridview  .  Gaurav Arora  .  G_arora  .  FileUploadControl  .  DataGrid  .  Code snippet  .  Asp.net  .  

    Post Feedback


    This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
    You must Sign In to post a response.
    Next Resource: Open any type of files using .net
    Previous Resource: Passing values from Child controls to parent controls in ASP.net and javascript
    Return to Discussion Resource Index
    Post New Resource
    Category: ASP.NET WebForms


    Post resources and earn money!
     
    More Resources



    dotNet Slackers

    About Us    Contact Us    Privacy Policy    Terms Of Use