Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Uploading file with Progress Bar

Uploading file with Progress Bar

In this article I am going to show how to upload a file with progress bar in asp.net .

Author Rank :
Page Views : 9260
Downloads : 665
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
UploadFileWithProgressBar.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


In this article I am going to show how we can upload file with progress bar. I posted articles about uploading file, but in this article I am showing uploading of file with progress bar. Here in this article I am upload two type files namely video and image. First user have to select  what type of file he/she want to upload and after uploading he can see uploaded file below in a datalist.

The aspx code for this is

<%@ 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>File Upload</title>

 

<link href="StyleSheet.css" rel="Stylesheet" type="text/css" />

    <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>

        <table cellpadding="0" cellspacing="0" width="80%" align="center" style="background: White;

            padding: 10px;" border="4">

            <tr>

                <td align="left" style="border: none;">

                    <div>

                        <h1>

                            Select File To Upload</h1>

                        <asp:Label ID="lblImageFile" Text="Your File" AssociatedControlID="ImageFile" runat="server"

                            CssClass="lbl" />

                        <asp:DropDownList ID="DListFileType" runat="server">

                            <asp:ListItem Text="Image" Value="Image"></asp:ListItem>

                            <asp:ListItem Text="Video" Value="Video"></asp:ListItem>

                        </asp:DropDownList>

                        <input id="ImageFile" contenteditable="false" runat="server" name="ImageFile" type="file"

                            style="width: 300px" />&nbsp;&nbsp;

                        <asp:Button ID="btnAddImage" runat="server" Text="Upload File" OnClientClick="return ProgressBar()"

                            OnClick="btnAddImage_Click" />

                        <br />

                        <br />

                        <asp:Label ID="lblError" runat="server" ForeColor="Red" Font-Bold="true" Visible="false"></asp:Label>

                        <br />

                        <br />

                        <asp:Button ID="btnShowImage" Text="Show Image" runat="server" OnClick="btnShowImage_Click" />

                        <asp:Button ID="btnShowVideo" Text="Show Video" runat="server" OnClick="btnShowVideo_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: Blue;

                                    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"></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","~/Images/{0}")%>' Style="width: 200px"

                                    runat="server" AlternateText='<%# Eval("Name") %>' />

                                <br />

                               

                            </ItemTemplate>

                        </asp:DataList>

                    </div>

                </td>

            </tr>

            <tr>

                <td>

                    <div class="bottomColumn">

                        <asp:DataList ID="DataListVideo" RepeatColumns="3" runat="server" Width="100%">

                            <ItemTemplate>

                                <object id="mediaPlayer" classid='clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95' standby='Loading....'

                                    type='application/x-oleobject' width="160px">

                                    <param name="movie" value="<%# Eval("Name","http://localhost/UploadFileWithProgressBar/Video/{0}")%>">

                                    <param name='animationatStart' value='false'>

<%-- Here your URL --%>

 

                                    <param name='transparentatStart' value='false'>

                                    <param name='autoStart' value='false'>

                                    <param name='showControls' value='true'>

                                    <param name='clickToPlay' value='true'>

                                    <param name="ShowStatusBar" value='true'>

                                    <param name="windowlessVideo" value='false'>

                                    <embed type="application/x-mplayer2" pluginspage="http://microsoft.com/windows/mediaplayer/en/download/"

                                        id="" name="mediaPlayer" class="MediaPlayerWidth" src="<%# Eval("Name","http://localhost/UploadFileWithProgressBar/Video/{0}")%>"> </embed>

 

<%-- Here your URL --%>

 

                                </object>

                            </ItemTemplate>

                        </asp:DataList>

                    </div>

                </td>

            </tr>

        </table>

    </div>

    </form>

</body>

</html>

 

This is the aspx.cs code

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;

using System.Data.SqlClient;

using System.Text;

using System.Collections.Generic;

using System.Linq;

using System.Diagnostics;

 

public partial class _Default : System.Web.UI.Page

{

    string DownloadFileType;

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnAddImage_Click(object sender, EventArgs e)

    {

        DownloadFileType = DListFileType.SelectedValue.ToString();

        string strFileName;

        HtmlInputFile htmlFile = (HtmlInputFile)ImageFile;

 

        if (htmlFile.PostedFile.ContentLength > 0)

        {

            string sFormat = String.Format("{0:#.##}", (float)htmlFile.PostedFile.ContentLength / 2048);

            ViewState["ImageName"] = htmlFile.PostedFile.FileName.Substring(htmlFile.PostedFile.FileName.LastIndexOf("\\") + 1);

            strFileName = ViewState["ImageName"].ToString();

            string sExtension = strFileName.Substring(strFileName.LastIndexOf(".") + 1);

 

            if (checkFileType(sExtension))  //Check for file types

            {

                if (DownloadFileType == "Image")

                {

                    htmlFile.PostedFile.SaveAs(Server.MapPath("~/Images/" + strFileName));

                }

                else if (DownloadFileType == "Video")

                {

                    htmlFile.PostedFile.SaveAs(Server.MapPath("~/Video/" + strFileName));                   

                }

                lblError.Visible = false;

                System.Threading.Thread.Sleep(8000);

                Label1.Visible = true;

                Label1.Text = "Upload successfull!";

                ShowImage();

                ShowVideo();

            }

            else

            {

                lblError.Visible = true;

                lblError.Text = "Please Check your file";

            }

        }

 

        else

        {

            lblError.Visible = true;

            lblError.Text = "Please Select any file to upload";

        }

    }

    private bool checkFileType(string FileExtension)

    {

        if (DownloadFileType == "Video")

        {

            switch (FileExtension.ToLower())

            {

                case "wmv":

                    return true;

                case "avi":

                    return true;

                case "mpg":

                    return true;

                case "wav":

                    return true;

                case "mid":

                    return true;

                case "asf":

                    return true;

                case "mpeg":

                    return true;

                case "dat":

                    return true;

                default:

                    return false;

            }

        }

        else if (DownloadFileType == "Image")

        {

            switch (FileExtension.ToLower())

            {

                case "gif":

                    return true;

                case "png":

                    return true;

                case "jpg":

                    return true;

                case "jpeg":

                    return true;

                default:

                    return false;

            }

        }

        return false;

    }

 

    protected void btnShowImage_Click(object sender, EventArgs e)

    {

        ShowImage();

    }

 

    public void ShowImage()

    {

        DirectoryInfo myImageDir = new DirectoryInfo(MapPath("~/Images/"));

        try

        {

            dlImageList.DataSource = myImageDir.GetFiles();

            dlImageList.DataBind();

        }

        catch (System.IO.DirectoryNotFoundException)

        {

            Response.Write("<script language =Javascript> alert('Upload File(s) First!');</script>");

        }

    }

 

    protected void btnShowVideo_Click(object sender, EventArgs e)

    {

        ShowVideo();

    }

 

    public void ShowVideo()

    {

        DirectoryInfo myVideoDir = new DirectoryInfo(MapPath("~/Video/"));

        try

        {

            DataListVideo.DataSource = myVideoDir.GetFiles();

            DataListVideo.DataBind();

        }

        catch (System.IO.DirectoryNotFoundException)

        {

            Response.Write("<script language =Javascript> alert('Upload File(s) First!');</script>");

        }

    }

 

}

 

When we run the application then the output will be as follows

UploadFileWithProgressBar1.JPG

Figure 1.

 

From DropDownlist user can select the type of file to be uploaded.

 

When uploading an image file. 

UploadFileWithProgressBar2.JPG 

 

Figure 2.

 

After uploading an image 

UploadFileWithProgressBar4.JPG 

 

Figure 3.

 

If user has selected video as the file type to be uploaded.

UploadFileWithProgressBar5.jpg

Figure 4.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rahul Kumar Saxena
Rahul shows great interests in working with Microsoft technologies. He specializes in the implementation of DataBase & Graphics. His area of expertise includes: C#, ASP.NET,ADO.NET,Windows Forms & Web Services. He hails from background , Master's in Computer Application. With programming he loves photography, traveling and reading books.
(Talabpur*)
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Thread implementation!! by quispe On November 29, 2009
Hello, I read your article and I feel great, but I have a query, when the ProgressBar is working, I can not move the window, and when I do this is blocked, as could implement threads in this demo?

I hope you can help, Thanks! : D

Enjoy!!

Johnny B.
Reply | Email | Modify 
i am getting an exception by hem On March 16, 2011
htmlFile.PostedFile.SaveAs(Server.MapPath("~/Images/" + strFileName)); on that preceeding line Could not find a part of the path 'C:\Documents and Settings\Administrator\Desktop\hem\pms\progressbar\Images\Surya_Anand.jpg'.
Reply | Email | Modify 
progress bar in .vb by mark On March 17, 2011
has anyone tried this in .vb? Or think that a c# to vb converter may work
Reply | Email | Modify 
Very nice... code for upload file with progressbar by krishna On October 12, 2011
Very nice... code for upload file with progressbar
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.