.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!



Home >> Code Snippets >> ASP.NET Controls >> Post New Resource Bookmark and Share

 Subscribe to Code Snippets

Showing progress with FileUpload Control

Posted By :Gaurav Arora      Posted Date :22/08/2009   Points :10   Category: ASP.NET Controls    URL: http://www.msdotnetheaven.com/forums
 


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>");
        }
    }
    
}

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.




  • Featured Articles


    Best Practices No 5: - Detecting .NET application memory leaks
    Memory leaks in .NET application have always being programmer's nightmare. Memory leaks are biggest problems when it comes to production servers. Productions servers normally need to run with least down time. Memory leaks grow slowly and after sometime they bring down the server by consuming huge chunks of memory. Maximum time people reboot the system, make it work temporarily and send a sorry note to the customer for the downtime. ... Read More
    .NET Best Practice No: 1:- Detecting High Memory consuming functions in .NET code
    One of the important factors for performance degradation in .NET code is memory consumption. Many developers just concentrate on execution time to determine performance bottle necks in a .NET application. Only measuring execution time does not clearly give idea of where the performance issue resides. Ok, said and done one of the biggest task is to understand which function, assembly or class has consumed how much memory. In this tutorial we will see how we can find which functions consume how much memory. This article discusses the best practices involved using CLR profiler for studying memory allocation.... Read More
    How to improve your LINQ query performance by 5 X times ?
    LINQ has been criticized by many early adopters for its performance issues. Well if you are just going to drag and drop using DBML code generator I am sure you will land up in to mess. Try doing this make a simple LINQ to SQL project using DBML and see your SQL profiler, I am sure you will never like to touch DBML code generator again. ... Read More
    Responses

    No response found. Be the first to respond this post

    Post Comment
    You must Sign In To post reply
    Find More code samples in C#, ASP.Net, Vb.Net and more Here

    Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend