Creating Progress Bar for FileUpload control

G_arora
Posted by in ASP.NET category on for Intermediate level | Views : 30130 red flag

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:
Introduction
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:
 
Description
Through-out this article you will learn with code how to use / create a progress bar for FileUplaod control.

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 C#:

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 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("");
                    System.Threading.Thread.Sleep(8000)
                    Label1.Text = "Upload successfull!"
                Catch generatedExceptionName As System.IO.DirectoryNotFoundException
                    createDir()
                End Try
            End If
        Else
            Response.Write("")
        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("")
    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("")
        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.
  • Page copy protected against web site content infringement by Copyscape

    About the Author

    G_arora
    Full Name: Gaurav Kumar Arora
    Member Level: Starter
    Member Status: Member,Microsoft_MVP
    Member Since: 9/7/2009 2:53:47 AM
    Country: India
    Gaurav Kumar Arora
    http://www.gaurav-arora.com
    MCA, M.Phill(Comp.Sc.),MCP, MCTS, Certified Scrum Master. Life time member of CSI (Computer Society of India)

    Login to vote for this post.

    Comments or Responses

    Posted by: Virendradugar on: 9/8/2009
    Hi,

    As you have said "The logic behind this is just to get the total time take for upload a file into server." I can not see a single line of code which is actually calculating the time required to upload and setting it to any of the java script variable.

    And what is 299 in the Java script function?

    Kindly explain.
    Posted by: G_arora on: 9/8/2009
    Virender,

    Its a series of articles, sorry to mention about the series.

    In next part(s) I will explain each and everything with Codes.

    Till then please be patience.

    Regards,
    Gaurav Arora
    Posted by: Vasanthmvp on: 8/17/2012 | Points: 25
    Hi,

    I think here we are just manipulating in such a way that user can see a vertical progress bar, which is getting executed on the client side(java script). Mean while, we are letting the process to go under sleep mode for 8 seconds. So, irrespective of the image content length the vertical bar gets completed in 8 sec and shows success message. Is there any other way to show the percentage of file uploaded based on the content length of the file.


    Regards,
    Awesome Coding!! :)
    Posted by: G_Arora on: 8/17/2012 | Points: 25
    Hi Vasanthmvp,

    As earlier I mentioned that this is a series of article. yes there are many ways to show/count content length while we are uploading file:

    Series of article contains all concepts like:
    Calculating time on the Broadband speed etc.


    Login to post response

    Comment using Facebook(Author doesn't get notification)