This example shows how to integrate an upload with progress bar into a codebehind page. It assumes you are using Visual Studio 2005.

 

   
1
 
Add Reference    
     

Add a reference to ABCUpload .NET (ABCUpload6).

You can do this by right clicking on your project and choosing Add Reference. You will find ABCUpload6 near the top of the '.NET Tab'.

If you do not add a reference to ABCUpload .NET you will not be able to use the ABCUpload classes in your project.

 

   
2
 
Progress Module    
     

Add the ABCUpload Progress Module to your web.config.

The configuration section you need to add is shown below in red. If you do not add this or if you put it in the wrong location then the progress bar may launch but it will not update or close.

<?xml version="1.0"?>
<configuration>
  <system.web>

    <httpModules>
      <add name="Progress" type="WebSupergoo.ABCUpload6.ProgressModule, ABCUpload6, Version=6.0.0.0, Culture=neutral, PublicKeyToken=572826f585f78c3a"/>
    </httpModules>


    ..... more configuration settings

Please note that there are other settings which you will probably want to change as well. These are detailed in the web.config section of the documentation. However this can be left until after the basic example has been implemented and tested.

 

   
3
 
Create File Upload Form    
     

Choose 'Add New Item...' from the 'Website' menu and select and add a Web Form.

Add a file input field and submit button to your form. The easiest way to do this is to drag these two controls out of the Toolbox window and drop them onto the page design.

You will find the 'Button' control on the 'Standard' section of the Toolbox.

You will find the 'Input (File)' control on the 'HTML' section of the Toolbox.

Right click on the file input control, get the properties and assign it a name. For the purposes of this example we'll assume you've given it the name 'myfile'.

If you don't have a file input element you will not be able to select any files. If you don't have a submit button there will be no obvious way to submit the upload. If your file field does not have a name you will not be able to easily reference it when you need to save your uploaded file.

 

   
4
 
Check File Upload Form    
     

Click on the HTML Tab for your aspx form and check that multipart form encoding is being used. Check also that you have set the name of the file input field correctly.

The attributes you need to check are shown below in red. If they are not present or correct you should add or change them.

If EnableEventValidation is not set to false then ASP.NET will complain because of changes made to the form action by our client side JavaScript. If the encoding type is not set to multipart then no files will be uploaded when the form is submitted. If the field name is wrong then your code will not be able to reference the uploaded file.

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

<!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">
      <title>Untitled Page</title>
</head>
<body>
  <form id="form1" encType="multipart/form-data" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <input id="File1" name="myfile" type="file" /></div>
    </form>
</body>
</html>

 

   
5
 
Add Codebehind to File Upload Form    
     

Double click on the submit button to bring up the codebehind page.

You will need to add the ABCUpload namespace.

You will need to add code to register the progress bar when the page is loaded and to save the file when the submit button is clicked.

The sections you need to add are shown below in red.

Note that the UploadedFile.Detach method (detailed in the Pure HTML Progress Bar Upload Example) is often a more efficient method to use for saving large uploaded files. The code here is designed for simplicity and robustness rather than optimal performance.

[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 WebSupergoo.ABCUpload6;

public partial class myupload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!ClientScript.IsClientScriptBlockRegistered("DoUpload")) {
            string theScript = "\r\n";
            theScript += "<script language=JavaScript>\r\n";
            theScript += "<!--\r\n";
            theScript += "function DoUpload(inForm) {\r\n";
            theScript += " if ((typeof(Page_BlockSubmit) == 'boolean') && (Page_BlockSubmit == true)) return;\r\n";
            theScript += " theFeats = 'height=160,width=600,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no';\r\n";
            theScript += " theUniqueID = Math.floor(Math.random() * 1000000) * ((new Date()).getTime() % 1000);\r\n";
            theScript += " window.open('progressbar.aspx?ProgressID=' + theUniqueID, theUniqueID, theFeats);\r\n";
            theScript += " inForm = inForm.document.forms[0];\r\n";
            theScript += " thePos = inForm.action.indexOf('?');\r\n";
            theScript += " if (thePos >= 0)\r\n";
            theScript += " inForm.action = inForm.action.substring(0, thePos);\r\n";
            theScript += " inForm.action += '?UploadID=' + theUniqueID;\r\n";
            theScript += " inForm.submit();\r\n";
            theScript += "}\r\n";
            theScript += "//-->\r\n";
            theScript += "</script>\r\n";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "DoUpload", theScript);
        }
        ClientScript.RegisterOnSubmitStatement(this.GetType(), "submit", "DoUpload(this);");

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Upload theUpload = new Upload();
        UploadedFile theFile = theUpload.Files["myfile"];
        if ((theFile != null) && (theFile.ContentLength > 0))
            theFile.SaveAs(theFile.WinSafeFileName);

    }
}

[VB]
Imports WebSupergoo.ABCUpload6

Partial Class WebForm1
    Inherits System.Web.UI.Page

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        If ClientScript.IsClientScriptBlockRegistered("DoUpload") = False Then
            Dim sc As String = vbCrLf
            sc = sc + "<script language=JavaScript>" + vbCrLf
            sc = sc + "<!--" + vbCrLf
            sc = sc + "function DoUpload(inForm) {" + vbCrLf
            sc = sc + " if ((typeof(Page_BlockSubmit) == 'boolean') && (Page_BlockSubmit == true)) return;" + vbCrLf
            sc = sc + " theFeats = 'height=160,width=600,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no';" + vbCrLf
            sc = sc + " theUniqueID = Math.floor(Math.random() * 1000000) * ((new Date()).getTime() % 1000);" + vbCrLf
            sc = sc + " window.open('progressbar.aspx?ProgressID=' + theUniqueID, theUniqueID, theFeats);" + vbCrLf
            sc = sc + " inForm = inForm.document.forms[0];" + vbCrLf
            sc = sc + " thePos = inForm.action.indexOf('?');" + vbCrLf
            sc = sc + " if (thePos >= 0)" + vbCrLf
            sc = sc + " inForm.action = inForm.action.substring(0, thePos);" + vbCrLf
            sc = sc + " inForm.action += '?UploadID=' + theUniqueID;" + vbCrLf
            sc = sc + " inForm.submit();" + vbCrLf
            sc = sc + "}" + vbCrLf
            sc = sc + "//-->" + vbCrLf
            sc = sc + "</script>" + vbCrLf
            ClientScript.RegisterClientScriptBlock(Me.GetType(), "DoUpload", sc)
        End If
        ClientScript.RegisterOnSubmitStatement(Me.GetType(), "submit", "DoUpload(this);")
    End Sub


    Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim theUpload As Upload = new Upload()
        Dim theFile As UploadedFile = theUpload.Files("myfile")
        If Not theFile Is Nothing And theFile.ContentLength > 0 Then
            theFile.SaveAs(theFile.WinSafeFileName)
        End If

    End Sub
End Class

   
6
 
Add Progress Bar Design    
     

We need to add a progress bar page.

Choose 'Add New Item...' from the 'Website' menu and select and add a Web Form. Name the form progressbar.aspx.

We need to insert the design for the form. Click on the HTML tab and insert the new head and body content as shown in red.

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

<!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>
  <title>Progress...</title>
  <meta http-equiv="expires" content="Tue, 01 Jan 1981 01:00:00 GMT">
  <% = Meta %>
  <script language="javascript">
  <!--
  if (<% = Percent %> >= 100) top.close();
  //-->
  </script>
 </head>
 <body bgcolor="#cccccc">
  <table border="0" width="100%">
   <tr>
    <td><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b>Uploading:</b></font></td>
   </tr>
   <tr bgcolor="#999999">
    <td>
     <table border="0" width="<% = Percent %>%" cellspacing="1" bgcolor="#0033ff">
      <tr><td><font size="1">&nbsp;</font></td></tr>
     </table>
    </td>
   </tr>
   <tr>
    <td>
     <table border="0" width="100%">
      <tr>
       <td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Estimated&nbsp;Time&nbsp;Left:</font></td>
       <td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><% = State %></font>
       </td>
      </tr>
      <tr>
       <td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Transfer&nbsp;Rate:</font></td>
       <td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><% = Kbps %> KB/sec</font></td>
      </tr>
      <tr>
       <td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Information:</font></td>
       <td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><% = Note %></font></td>
      </tr>
      <tr>
       <td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Uploading&nbsp;File:</font></td>
       <td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><% = FileName %></font></td>
      </tr>
     </table>
    </td>
   </tr>
   <tr>
   </tr>
  </table>
 </body>

</html>

 

   
7
 
Add Progress Bar Code    
     

Next we need to insert the code to populate the page with data.

Open the codebehind for the progressbar.aspx file.

The sections you need to add are shown below in red.

[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 WebSupergoo.ABCUpload6;

    public partial class progressbar : System.Web.UI.Page
    {
        protected string State;
        protected string Meta;
        protected string Percent;
        protected string Kbps;
        protected string Note;
        protected string FileName;

    
        protected void Page_Load(object sender, EventArgs e)
        {
            Progress theProgress = new Progress(Request.QueryString["ProgressID"]);
            
            string theID = theProgress.ID.ToString();
            string theMins = ((int)theProgress.SecondsLeft / 60).ToString();
            string theSecs = ((int)theProgress.SecondsLeft % 60).ToString();
            Meta = "<meta http-equiv=\"refresh\" content=\"2,progressbar.aspx?ProgressID=" + theID + "\">";
            Percent = theProgress.PercentDone.ToString();
            Kbps = Math.Round(theProgress.BytesPerSecondCurrent / 1024, 1).ToString();
            string theKbdone = Math.Round((double)theProgress.BytesDone / 1024, 1).ToString();
            string theKbtotal = Math.Round((double)theProgress.BytesTotal / 1024, 1).ToString();
            Note = theProgress.Note;
            FileName = theProgress.FileName;
            if (theProgress.Finished) Meta = "";
            State = theMins + " min " + theSecs + " secs (" + theKbdone + " KB of " + theKbtotal + " KB uploaded)";

        }
    }

[VB]
Imports WebSupergoo.ABCUpload6

Public Class progressbar
    Inherits System.Web.UI.Page

    Protected State As String
    Protected Meta As String
    Protected Percent As String
    Protected Kbps As String
    Protected Note As String
    Protected FileName As String

    Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim theProgress As Progress = New Progress(Request.QueryString("ProgressID"))

        Dim theID As String = theProgress.ID.ToString()
        Dim theMins As String = CInt(theProgress.SecondsLeft / 60).ToString()
        Dim theSecs As String = (CInt(theProgress.SecondsLeft) Mod 60).ToString()
        Meta = "<meta http-equiv=""refresh"" content=""2,progressbar.aspx?ProgressID=" + theID + """>"
        Percent = theProgress.PercentDone.ToString()
        Kbps = Math.Round(theProgress.BytesPerSecondCurrent / 1024, 1).ToString()
        Dim theKbdone As String = Math.Round(CDbl(theProgress.BytesDone) / 1024, 1).ToString()
        Dim theKbtotal As String = Math.Round(CDbl(theProgress.BytesTotal) / 1024, 1).ToString()
        Note = theProgress.Note
        FileName = theProgress.FileName
        If theProgress.Finished = True Then Meta = ""
        State = theMins + " min " + theSecs + " secs (" + theKbdone + " KB of " + theKbtotal + " KB uploaded)"
    End Sub

End Class

 

   
8
 
Test    
     

Finally set your main form as the startup page and run your project.

 

   
9
 
Notes    
     

ABCUpload will happily coexist with server side controls.

However be careful of anything that might require a server postback.

A postback is a form submission and if you have a file selected into a file input field then the entire file will have to be uploaded for this postback to occur.