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.