ABCUpload for .NET 2.0 Reference Guide

ABCUpload .NET 2.0 Reference Guide

ABCUpload .NET gives you advanced control over file upload to Internet Information Services (IIS) using standard HTML forms.

ABCUpload offers a number of advanced features such as Pure HTML Progress Bar™ support, GigUpload™ technology for massive uploads, Corruption Autofix™, Unicode compliant and MacBinary compatible. WebSupergoo - sticking the web together.

© 2005 WebSupergoo

Every effort has been made to ensure that the information in this manual is accurate. However WebSupergoo makes no guarantees about the accuracy or quality of this manual or any software it describes.

Windows, Windows NT, Windows 95, Windows 2000, Windows XP, Windows 2003, Internet Information Services, Visual Basic and Visual Studio are trademarks of Microsoft Corporation.


What is ABCUpload?

ABCUpload is a .NET assembly that allows sophisticated control over the upload of files from a web browser to your IIS web server. It requires no client side software and operates on the server via standard multipart HTML forms as defined in RFC 1867.

ABCUpload .NET consists of a number of classes including our Progress Module which drives the Pure HTML Progress Bar™. This interoperates seamlessly with standard .NET request classes.

For advanced control over the upload process ABCUpload provides a number of other classes to supplement the standard .NET request classes. These let you perform massive uploads via our proprietary GigUpload™ engine, automatically fix corrupt uploads and automatically decode MacBinary encoded uploads.

You can use ABCUpload from any .NET language including VB.NET and C#. ABCUpload runs on Windows 2000 and Windows XP.


Who is this document for?

This document is written as a guide to and reference material for the ABCUpload component. It assumes basic knowledge of ASP.NET and a working knowledge of C#, HTTP and HTML. It also assumes you know how to set up and configure Microsoft's Internet Information Services (IIS).


What do I need to use it?

You need a PC running Windows 2000, Windows XP, Windows 2003 or later.

You'll need to ensure that you have the .NET 2.0 framework installed.

Finally you'll need ABCUpload .NET itself.


What's New?

We've rewritten the whole of ABCUpload in C#. It's 100% CLS compliant and 100% managed code for unsurpassed performance, control and stability.

This rewrite has given us the opportunity to completely update the core upload engine using our proprietary GigUpload™ technology. ABCUpload was always fast and efficient but now it's even more so - if you want to do simultaneous Gigabyte uploads you can do them using ABCUpload .NET.

We've updated our Pure HTML Progress Bar™ for even better feedback. You can customize the messages and even see what file's currently being uploaded. Combine this with our new GigUpload technology and you've got an unbeatable package!

ABCUpload integrates perfectly with ASP.NET. You can interoperate with standard .NET upload classes taking advantage of only the features within ABCUpload that you require. You can use the Pure HTML Progress bar in conjunction with the standard HttpRequest Files collection. You can use the ABCUpload Upload class to access advanced upload features. You can even use the Pure HTML Progress bar in conjunction with other kinds of HTTP requests such as normal form submissions.


Pure HTML Progress Bar™

File uploads are great because they are so compatible. Because they use standard HTTP virtually every web browser can do them and firewalls don't get in the way. If your user is on a fast connection or is uploading small files the process is instantaneous. You choose a file - you hit submit - your file arrives on the server.

Problems only start to arise when you want to upload large files or your users are on slow connections. When clients submit their file it may take seconds or minutes to send to the server. Because browsers don't display progress bars your users may get confused or frustrated and give up rather than completing their upload. The obvious solution to this would be to give the user a dedicated progress bar but client side code brings in major problems of incompatibility.

ABCUpload utilizes a Pure HTML Progress Bar. It keeps track of every upload and allows you to watch how much of your file has been uploaded with absolutely no components installed on the client. If you can upload; you can use our progress bar - it's Pure HTML.

.


GigUpload™ Technology

ABCUpload .NET incorporates our proprietary GigUpload Technology. Our Progress Module picks up ongoing uploads and uses a number of high performance techniques to allow uploads of virtually unlimited size. Whether you want to upload KB or GB your choice has to be ABCUpload!

The following graph shows memory (% Committed Bytes) and processor use (% Processor Time) for a large upload under ASP.NET using GigUpload. Memory use is in red and processor load is in green.

Memory use is constant and negligible. Processor load is also slightly reduced and because the processing of the upload is a continuous multithreaded process again the load is more constant.


Corruption Autofix™

Much of ABCUpload works via the ABCUpload Progress Module. This is a .NET HTTP Module designed to intercept page requests. It manages the data that's been received to ensure optimal use of memory and automatically fixes corrupt uploads.

ASP.NET is designed to handle uploads conforming to RFC 1867. Client browsers are supposed to submit multipart forms in this format but unfortunately many contain bugs which result in corrupt uploads being submitted. ABCUpload has been established many years and during this time we've adapted our code to handle every kind of corrupt upload we've ever come across.

Rather than present invalid data to ASP.NET ABCUpload pre-vets uploads and when it finds corruption it automatically fixes it before passing the data through to ASP.NET.


Integrated with ASP.NET

ABCUpload integrates perfectly with ASP.NET. You can interoperate with standard .NET upload classes taking advantage of only the features within ABCUpload that you require.

You can use the Pure HTML Progress bar in conjunction with the standard HttpRequest Files collection.

You can use the ABCUpload Upload class to access advanced upload features.

You can even use the Pure HTML Progress bar in conjunction with other kinds of HTTP requests such as normal form submissions.


120% MacBinary Compatible™

You have to handle MacBinary to allow uploads from most Macintosh browsers. Many other components claim to be able to support MacBinary but their support consists of stripping out what they consider relevant and then throwing away everything else.

So how come ABCUpload is 120% MacBinary compatible? Well ABCUpload is the only product to use all the information available. If you upload a Macintosh file to a server running Services for Macintosh (SFM) your Mac file will appear just like it left your client - icons, previews and file name completely intact. ABCUpload is the only product to do this so we gave it an extra 10%. Additionally Internet Explorer sometimes incorrectly codes the MacBinary so ABCUpload has to read the corrupted format. As this happens about 10% of the time we gave ABCUpload another 10%. ABCUpload - 120% MacBinary compatible.

In detail...

Macintosh files are different from Windows or UNIX files in three main ways:

  • Every file consists of two separate streams or forks. The data fork holds the basic file information that you would find in a Windows file. The resource fork contains a database of other associated information such as picture previews, notes and icons. So a BMP image might contain the BMP in the data fork and a icon, preview and copyright note in the resource fork.
  • Macintosh files do not contain a file type extension. Instead they have a hidden type and creator code.
  • Macintosh file names can contain almost any character except for the colon character. This means that it is common to have Macintosh files containing slashes, question marks and asterisks.

When Internet Explorer uploads a file from a Macintosh it chooses to put all this information together into one big stream encoded as MacBinary. ASP.NET doesn't understand this format at all and MacBinary encoded uploads will appear to have been corrupted if you use standard .NET functionality. Some ASP upload components claim to be MacBinary compatible - they just rip out the data fork. However if you do this you loose all sense of what type of file was uploaded and some types of files such as EPS and QuickTime movies can be completely destroyed by this process.

At a basic level we use the creator and type properties to infer the file type. Then we take this one step further. Microsoft has given us the ability to handle this kind of file completely correctly. So if you use ABCUpload to save a MacBinary file to an NTFS formatted disk you can maintain complete integrity of data fork, resource fork, file type and creator. If you look at such a file from Windows it will look like a standard file (e.g. JPEG, DOC etc.) but if you serve this file to Macintosh users using Services for Macintosh (SFM) they will see the original file completely intact.


Advanced Technical Design

When we create server side controls we do it properly. We code in C# for unsurpassed performance, control and stability. All our classes are 100% CLS compliant and 100% Managed*.

Uploads are only copied to memory when required. This means that even for large uploads ABCUpload will use only a small amount of memory. Caching on disk is invisible to the user and uses advanced Windows techniques to ensure that the division of data between disk and memory is handled optimally.

ABCUpload is multithreaded to take full advantage of multiple processors. In particular, time wasteful operations such as disk access, are serialized to other threads to ensure that no bottlenecks occur.

* All core operations within our .NET products are 100% managed code and most users will only ever want to use these core operations. However .NET does not currently support all the features that the Windows API allows access to and the only way to get at these features is via unmanaged calls into the OS. We don't want to limit you unnecessarily so we isolate and clearly mark any methods that might use unmanaged code. If you want to use these methods you will need to ensure that your ASP.NET permission allows you to call unmanaged code via ABCUpload.

In ABCUpload the only method that uses unmanaged code is the UploadedFile.SaveSFM method for saving files in Services for Macintosh format.


Unicode Compliant

The Internet is international. You are as likely to get uploads from people in Japan as you are from people in the United States. Different countries use different character systems and your upload component has to be able to handle both Japanese and English characters.

ABCUpload handles all this for you transparently via Unicode support. For example a visitor uploads a file with a Japanese name - all the file details will arrive intact. You can decide whether you want to convert the name into something more URL friendly or if you want to use the Japanese name or a derivation of it.

Of course ABCUpload isn't specific to Japanese. Unicode covers every character system in the world.


File Upload Background

So what is File Upload and how does it work? File Upload or HTTP upload allows your visitors to send files to your web server using standard forms. In the same way that there are form elements that allow you to enter text and others that allow you to choose items from a list there is a form element that allows you to choose a file.

So what does a File Upload form element look like? Well here's a small and nonfunctional form containing a file input field.

File Upload was not supported in Internet Explorer 3.0 but was soon afterwards added in version 3.02. It is available in Netscape Navigator from version 2.02 onwards. So the great advantage of HTTP upload is that upload facilities are standard on virtually any browser that will come to your web site.

So what does the HTML look like? Well, much like any other piece of form HTML. Here's the code for the above.

<form method="post" action="file-upload-1.htm"
name="submit" enctype="multipart/form-data">
<input type="file" name="fileField"><br><br>
<input type="submit" name="submit" value="submit"><br>
</form>

There are only a couple of real differences. The input type of the upload is 'file' rather than 'text'. The 'enctype' of the form is 'multipart/form-data'. Multipart form data is an Internet standard (covered by RFC 1867) for sending lots of different types of information over the Internet as one bundle.

After the upload form has been submitted to the server we have to get the server to extract the file from the upload. You can do this using standard ASP.NET components but you should bear in mind that file upload is not as simple as it might seem. Just as one example, some browsers encode files before transmitting them! Internet Explorer on MacOS uploads files encoded as MacBinary to allow special Mac specific features to be transmitted. While Mac browsers will normally make up only 10% of your visitors, you should bear in mind your audience. In some picture related industries like publishing you may find that this proportion approaches 100%.

A related issue is that you can't really rely on either the file name or the mime type of the file as provided to you. Because of the cross platform nature of the industry a text file may be named 'readme' or 'readme.txt' or even 'readme 10\10\99'. Because the mime type is determined by the browser it could be anything from 'text/plain' to 'application/x-macbinary' to something completely meaningless. You have to make decisions on a case by case basis depending on what you are trying to do.

ABCUpload is designed to work around these problems invisibly so that you don't have to worry about them.


Path Interpretation

ABCUpload lets you specify save locations using a number of convenient formats. You can specify such locations as absolute paths or as URLs and ABCUpload will automatically resolve any references for you.

ABCUpload will interpret the following paths as absolute references.

[C#]
using WebSupergoo.ABCUpload6;
Upload theUpload = new Upload();
UploadedFile theFile = theUpload.Files["filefield"];
theFile.SaveAs("h:\\mydir\\myfile.txt");
theFile.SaveAs("h:/mydir/myfile.txt");
theFile.SaveAs("//myserver/mydir/myfile.txt");
theFile.SaveAs("\\\\myserver\\mydir\\myfile.txt");

[VB]
Imports WebSupergoo.ABCUpload6
Dim theUpload As Upload = New Upload()
Dim theFile As UploadedFile = theUpload.Files("filefield")
theFile.SaveAs("h:\mydir\myfile.txt")
theFile.SaveAs("h:/mydir/myfile.txt")
theFile.SaveAs("//myserver/mydir/myfile.txt")
theFile.SaveAs("\\myserver\mydir\myfile.txt")

It will interpret the following paths as relative URLs and will convert them to absolute paths before saving the file in the appropriate location.

[C#]
using WebSupergoo.ABCUpload6;
Upload theUpload = new Upload();
UploadedFile theFile = theUpload.Files["filefield"];
theFile.SaveAs("myfile.txt");
theFile.SaveAs("uploads/myfile.txt");
theFile.SaveAs("../images/myfile.jpg");

[VB]
Imports WebSupergoo.ABCUpload6
Dim theUpload As Upload = New Upload()
Dim theFile As UploadedFile = theUpload.Files("filefield")
theFile.SaveAs("myfile.txt")
theFile.SaveAs("uploads/myfile.txt")
theFile.SaveAs("../images/myfile.jpg")

ABCUpload decides whether a path should be interpreted as a URL or as an absolute file path using a simple heuristic. If the path...

  • contains a colon it will be interpreted as an absolute path
  • contains a backslash it will be interpreted as an absolute path
  • starts with "//" it will be interpreted as an absolute UNC path
  • otherwise it will be assumed to be a URL


Web.Config

A number of configuration settings become very relevant when performing uploads. These can be changed by adding sections or values into the Web.Config file. A typical configuration section is given below.

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

  <compilation>
    <assemblies>
      <add assembly="ABCUpload6, Version=6.0.0.0, Culture=neutral, PublicKeyToken=572826f585f78c3a" />
    </assemblies>
  </compilation>

  <httpRuntime
    maxRequestLength="1048576"
    executionTimeout="3600"
  />

  <sessionState
    timeout="60"
  />
  ...

httpModules sub-tag

The Progress Module is required for the Pure HTML Progress Bar, for GigUpload and for Corruption Autofix functionality. The Progress Module is a .NET HTTP Module designed to intercept page requests and preprocess them before passing them on to ASP.NET.

To integrate the Progress Module into your ASP.NET application you need to add it using a line in the httpModules subsection of the web.config file. This is shown in the example web.config file above.

compilation sub-tag

To integrate and use ABCUpload objects into your ASP.NET application you need to add a reference to the assembly (stored in the GAC) using a line in the compilation subsection of the web.config file. This is shown in the example web.config file above

httpRuntime maxRequestLength

This attribute is used to limit the size of uploads by rejecting any which exceed a certain limit. The limit refers to the total size of the HTTP upload in KB (approximately equal to the sum of all the files being upload). You should set a sensible limit here to stop malicious visitors using up your bandwidth by uploading excessively large files.

If the size of an upload is too great the server will refuse to accept it. Because the server is refusing the request the uploading browser will report that the submission page is not available. This is a client side error message rather than a server side error message and it means that you cannot normally provide a sensible error message to users if they submit files which are too large.

However using ABCUpload you can report back a sensible error message via a progress window. If you believe that visitors may attempt to perform uploads greater than the maximum you should use the progress bar and the note on the progress window will inform your visitor why their upload has been rejected.

In the example web.config file above the maxRequestLength is set to 1 GB.

httpRuntime executionTimeout

The execution time-out refers to the number of seconds an ASP.NET page is given before the operation is assumed to have failed and the page terminated. If you are uploading a large file the code that is receiving the transfer may time out before the file has been completely uploaded.

In the example web.config file above the executionTimeout is set to one hour.

sessionState timeout

The session time-out refers to the number of minutes before the user session is aborted. If a large file is being uploaded it is desirable to maintain the session state. The session time-out should always be longer than the amount of time you expect uploads to take. Note that this value is only relevant if you have session state enabled.

In the example web.config file above the sessionState is set to one hour.

processModel responseDeadlockInterval

The responseDeadlockInterval is specified in the machine.config file and defaults to three minutes. It specifies the time interval after which the process will be restarted if no responses have been made and requests are still queued.

Under ASP.NET requests that take longer than the deadlock interval can cause problems under some very specific circumstances. Sometimes a client may make multiple page requests which ASP.NET may queue one after the other. If the first request in the queue takes longer than the deadlock interval then ASP.NET will mistakenly assume the whole process is deadlocked and restart it. These types of situation are very unusual and are more commonly encountered in test environments than real world ones.

For this situation to arise a client must make multiple uploads simultaneously. At least two uploads must take longer than the timeout. The client must make other page requests at the same time which IIS must decide to queue (whether it decides to queue them or not depends on whether IIS thinks they form part of the same session). These queued requests must not time out or be dismissed on the client side. Neither the client nor any other visitors must make other aspx page requests during this time.


ABCUpload Config

ABCUpload is an advanced piece of software. The default settings are generally all you will need but if you require you can add in a configuration section to the web.config file to fine-tune your upload.

Web.Config Structure

There are three sections within the abcupload section group - the notes section, the queryfields section and the advanced section. This is an example of a configuration file you might use. In this case all fields are set to their default values.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<configSections>
<sectionGroup name="websupergoo.abcupload">
<section name="advanced" type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="notes" type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="queryfields" type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</sectionGroup>
</configSections>

<websupergoo.abcupload>
  <advanced
    enableProgressBar="true"
    fixCorruptUploads="true"
    enableLargeUploads="true"
    multiThreaded="true"
    optimization="true"
    chunkSize="8192"
    tempDirectory=""
    logExceptions="true"
    serial=""
  />
  <notes
    exception = "An error occurred. {0}"
    connecting = "Connecting..."
    gettingSize = "Getting upload size..."
    checkingSize = "Checking upload size..."
    preloading = "Getting preloaded data..."
    transferring = "Transferring data..."
    finishing = "Finishing..."
    uploadStopped = "Upload stopped unexpectedly..."
    uploadTooLarge = "Upload size is greater than the maximum allowed..."
  />
  <queryfields
    uploadID = "UploadID"
    dumpPath = ""
  />
</websupergoo.abcupload>

<system.web>
... web configuration section

Notes Section

The notes section allows you to change the notes displayed in the Pure HTML Progress Bar.

Attribute | Description
connecting | The text to use before the first chunk of data from the upload has been received.
gettingSize | The text to use while the size of the upload is being established.
checkingSize | The text to use while the size of the upload is being checked.
preloading | The text to use while the first chunk of data is being received.
transferring | The text to use while subsequent chunks of data are being received
finishing | The text to use when all the data has been received and the upload is being processed.
uploadStopped | The text to use if data transfer terminated prematurely (typically if the visitor clicks on the stop button during an upload).
uploadTooLarge | The text to use if the upload was larger than the value specified as part of the httpRuntime maxRequestLength.
exception | The text to use if an unexpected exception occurs. The exception message is displayed in place of the string "{0}".

QueryFields Section

The queryfields section gives you control over the query fields that ABCUpload checks for in the URLs of posted forms. It is extremely unlikely that you will need to change these fields.

Attribute | Description
uploadID | The query string field to use to determine the ID for the upload.
dumpPath | The query string field to use to determine the path for an upload dump file to be used in place of the posted data.

Advanced Section

The advanced section allows you to change internal parameters used within ABCUpload.

Attribute | Description
enableProgressBar

This value defaults to true to indicate that the Progress Module should intercept ongoing uploads. When set to false the ABCUpload will pass through all uploads without interception.
fixCorruptUploads

This value defaults to true to indicate that the Progress Module should fix corrupted uploads when they are intercepted. When set to false the upload data is passed through unmodified.
enableLargeUploads

This value defaults to true to indicate that GigUpload should be enabled.

When GigUpload is enabled you should use the Upload object Files collection in place of the HttpUpload Files collection. If you want full interoperability between the Progress Module and the standard HttpRequest Files collection you can set this value to false.

You should be using the Pure HTML Progress Bar if you want to enable GigUpload. The Progress Module is required so that the ongoing upload can be intercepted. The query string upload ID is required so that ABCUpload can distinguish between file upload queries and other web page queries.

In the example web site this attribute is set to true.
multiThreaded

The default behavior is to process upload data on a separate thread from the one that receives it. Set this attribute to false to process and receive data on the same thread.
optimization

The default behavior is to use custom heuristics for accelerated processing of uploads. Set this attribute to false to disable these heuristics.
chunkSize

The chunk size determines how much upload data is read at one time. It effectively determines the granularity of the progress bar. Smaller values allow greater precision in keeping track of progress but place a greater overhead on the server. The default value is 8192 (0x2000) bytes which means that the progress bar will increment in chunks 8 KB in size.
tempDirectory

The temporary directory to use if GigUpload is enabled.
logExceptions | Exceptions are always passed through to the ASPX page. If you set this attribute to true then all exceptions from within ABCUpload will be logged in the Application Event Log before being re-thrown.
serial

You will normally install a serial key for ABCUpload by entering it into the ABCSettings application. However on shared servers this may not be possible and instead you may wish to register the serial key by entering it into your web.config file.

You can either enter a full license key which you will be sent when you purchase or you can insert a trial license key copied from ABCSettings.


Recreating Uploads

ABCUpload allows you to save and re-create uploads for debugging purposes. This facility is disabled by default and you must make changes to the Web.Config file to allow it to be used.

The first step in re-creating an upload is to save the raw upload data. This is simply accomplished by creating an Upload object and calling the Save method. Your code might look as simple as this.

[C#]
using WebSupergoo.ABCUpload6;
Upload theUpload = new Upload();
theUpload.Save "c:\\mydump.txt"

[VB]
Imports WebSupergoo.ABCUpload6
Dim theUpload As Upload = New Upload()
theUpload.Save "c:\mydump.txt"

To recreate an upload you must must alter the Web.Config file to tell ABCUpload what file to read. The queryfields section of the configuration file contains the dumpPath attribute which determines which query field to check for a saved upload file. So you might choose to insert the following text.

...
<websupergoo.abcupload>
<queryfields dumpPath = "DumpPath" />
</websupergoo.abcupload>
...

To trigger the recreation you then need to submit your form passing the file path in the query string. So you might simply link to the following page.

http://localhost/myformprocessor.aspx?DumpPath=c:\mydump.txt

When this page is requested the ABCUpload Progress Module will intercept the request. However instead of passing in the uploaded data it will read the data from the specified file and pass this through instead.


Event Logging

ABCUpload uses the Application Event Log to report important information.

  • When the component is successfully installed it will report this via an information event
  • If error logging is enabled in ABCUpload Config exceptions will be logged as warnings
  • Serious errors or inconsistencies in the environment will be logged as errors

For example if the component is unable to create a temporary file for caching uploads it will log an error "Unable to create temporary file". This kind of error will affect server performance but is not fatal.


Installation

The easiest way to install ABCUpload is to use the installer. The installer performs the following core functions.

  • Places the ABCUpload6.DLL assembly into the Global Assembly Cache (GAC)
  • Creates all necessary Event Logging and installation preferences
  • Installs the ABCSettings application

Under some circumstances you may wish to install ABCUpload manually. At a minimum you can place the ABCUpload6.DLL assembly into the bin directory of your web site. A copy of the DLL is available in the ImageGlue .NET installation directory.

However if you do this the full installation procedure will not have been followed. This has the following consequences:

  • Assuming you have standard permissions set up then ABCUpload will not be able to report warnings via the Application Event Log
  • No installation serial key will have been created and so the 30 day trial period will not be available

You can install a serial key using the web.config file. For details see the serial property in the ABCUpload Configuration section of this document.


Troubleshooting

We don't expect you to have any problems with our software but if you do we offer a full level of support as standard. However if you need an extra level of security we offer a Platinum Level Support program offering a priority channel through to our engineers.

Your first port of call should be to check out the FAQ on our website. If it doesn't cover your particular query you can mail us via the email addresses given on our web site. We prefer queries via email as technical issues are often complicated and require some thought on our side as well as yours. However if you need to telephone then numbers are listed on our web site.

Remember to tell us what Operating System you're on and what version of ABCUpload you're using. You can get the exact version of ABCUpload by getting properties on the ABCUpload6.DLL file.

If the problem is occurring in code you've written we'll probably start by asking you if it occurs in the example web pages which were installed with ABCUpload. This is so we can separate out installation and configuration issues from coding issues. You may wish to try the example pages out so that you can tell us in advance. Just create a new virtual directory and select the folder which contains the example code.

Please give us a precise description of what's gone wrong. If something's working partially please tell us what parts are working and what parts are not. If you have any theories or suspicions about what's going on please do tell us. Also tell us about any unusual software or configuration that might be relevant.

If the problem appears to be due to a corrupt or nonstandard upload you may wish to save a dump of the upload using the Upload.Save method and then send it through to us for analysis.


Example Introduction

The examples in this section demonstrate how to use ABCUpload .NET. They take you through from the most basic of uploads to a full featured upload with progress bar. The structure of the HTML and ASPX pages is designed to be as simple and modular as possible to avoid distracting from the basic functionality.

The modularity of the code means that you can just copy individual pages and insert them into your own projects. Note that you will also need to make changes to your web.config file.

For full integration with ASP.NET you may wish to re-implement the pages using more sophisticated techniques such as code-behind files and data binding.
web
web.config

This is a minimal example of the web.config file required for ABCUpload .NET. For further information see the web.config and ABCUpload config sections of this document.

[C#]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>

    <!-- HTTP MODULES
    The ABCUpload Progress Module is core to
    many features of ABCUpload.
    It intercepts requests and processes them
    appropriately. The Progress Module supplies
    the functionality for the Pure HTML Progress
    Bar, GigUpload and Corruption Autofix.
    If the progress module is not installed
    these features will not be available.
    -->
    <httpModules>
      <add name="Progress" type="WebSupergoo.ABCUpload6.ProgressModule, ABCUpload6, Version=6.0.0.0, Culture=neutral, PublicKeyToken=572826f585f78c3a"/>
    </httpModules>

    <!-- HTTP RUNTIME
    ASP.NET uses a maximum upload size set to
    a default designed to prevent Denial of
    Service (DOS) attacks. Here we increase
    the maximum request size to 1 GB.
    -->
    <httpRuntime
      maxRequestLength="1048576"
      executionTimeout="600"
    />

    <!-- COMPILATION
    Because we will be creating objects based
    on classes within the ABCUpload .NET assembly
    we need to reference the assembly within our
    config file. This is not necessary if the
    assembly is installed in the bin directory
    rather than the Global Assembly Cache (GAC).
    -->
    <compilation defaultLanguage="c#">
      <assemblies>
        <add assembly="ABCUpload6, Version=6.0.0.0, Culture=neutral, PublicKeyToken=572826f585f78c3a" />
      </assemblies>
    </compilation>

  </system.web>
</configuration>

[VB]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>

    <!-- HTTP MODULES
    The ABCUpload Progress Module is core to
    many features of ABCUpload.
    It intercepts requests and processes them
    appropriately. The Progress Module supplies
    the functionality for the Pure HTML Progress
    Bar, GigUpload and Corruption Autofix.
    If the progress module is not installed
    these features will not be available.
    -->
    <httpModules>
      <add name="Progress" type="WebSupergoo.ABCUpload6.ProgressModule, ABCUpload6, Version=6.0.0.0, Culture=neutral, PublicKeyToken=572826f585f78c3a"/>
    </httpModules>

    <!-- HTTP RUNTIME
    ASP.NET uses a maximum upload size set to
    a default designed to prevent Denial of
    Service (DOS) attacks. Here we increase
    the maximum request size to 1 GB.
    -->
    <httpRuntime
      maxRequestLength="1048576"
      executionTimeout="600"
    />

    <!-- COMPILATION
    Because we will be creating objects based
    on classes within the ABCUpload .NET assembly
    we need to reference the assembly within our
    config file. This is not necessary if the
    assembly is installed in the bin directory
    rather than the Global Assembly Cache (GAC).
    -->
    <compilation defaultLanguage="vb">
      <assemblies>
        <add assembly="ABCUpload6, Version=6.0.0.0, Culture=neutral, PublicKeyToken=572826f585f78c3a" />
      </assemblies>
    </compilation>

  </system.web>
</configuration>


Basic Upload Example

Basic Upload

This example shows how a basic upload works. It assumes that minimal configuration settings in the web.config file are implemented.
HTML
basicupload.htm

To start with you need an HTML form with a file field in it. Note that only multipart forms support file upload - hence enctype="multipart/form-data". If you try to upload a file from a form that isn't multipart encoded you will not receive any files.

This page submits data to basicupload.aspx.

<html>
<body>
<form method="post" action="basicupload.aspx" enctype="multipart/form-data">
<input type="file" name="filefield"><br>
<input type="submit" name="submit" value="submit">
</form>
<body>
</html>

ASP
basicupload.aspx

Our ASPX Page simply creates an Upload object and saves the uploaded file out into the 'write' directory as 'myupload.dat'.

ABCUpload automatically detects that the location you're specifying is a URL and automatically resolves it into a file path. However you can equally well use an absolute file path if you prefer.

[C#]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<%
Upload theUpload = new Upload();
theUpload.Files["filefield"].SaveAs("write/myupload.dat");
%>

<html>
<body>
File uploaded...
</body>

[VB]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<%
Dim theUpload As Upload = New Upload()
theUpload.Files("filefield").SaveAs("write/myupload.dat")
%>

<html>
<body>
File uploaded...
</body>


Two Image Upload Example

Two Image Upload

This example uploads two image files to show how to interoperate between ABCUpload and the standard ASP.NET classes. It assumes that minimal configuration settings in the web.config file are implemented.
HTML
imageupload.htm

All we need is a multipart HTML form with two file fields in it. This page submits data to imageupload.asps.

<html>
<body>
<form method="post" action="imageupload.aspx" enctype="multipart/form-data">
<input type="file" name="image1"><br>
<input type="file" name="image2"><br>
<input type="submit" name="submit" value="submit">
</form>
<body>
</html>
ASP
imageupload.aspx

We create an Upload object and specify some variables. We'll be using one ABCUpload UploadedFile object and one ASP.NET HttpPostedFile object to show how we can use both at the same time. We could reduce the amount of code considerably if we made use of ABCUpload added functionality but the aim for this example is to show how both objects can be used identically.

First we get a reference to our file object by referencing the Files collection within the Upload object. We check that some data has been uploaded and if so we work out a destination file name and then save the file to this location. The code using the standard ASP.NET classes is identical.

[C#]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<%
Upload Upload = new Upload();
UploadedFile theFile1;
HttpPostedFile theFile2;
string thePath;

theFile1 = Upload.Files["image1"];
if (theFile1.ContentLength > 0) {
  thePath = System.IO.Path.GetFileName(theFile1.FileName);
  thePath = Server.MapPath("write/") + thePath;
  theFile1.SaveAs(thePath);
}

theFile2 = Request.Files["image2"];
if (theFile2.ContentLength > 0) {
  thePath = System.IO.Path.GetFileName(theFile2.FileName);
  thePath = Server.MapPath("write/") + thePath;
  theFile2.SaveAs(thePath);
}
%>

<html>
<body>
Images uploaded...
</body>
</html>

[VB]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<%
Dim Upload As Upload = New Upload()
Dim theFile1 As UploadedFile
Dim theFile2 As HttpPostedFile
Dim thePath As String

theFile1 = Upload.Files("image1")
If theFile1.ContentLength > 0 Then
  thePath = System.IO.Path.GetFileName(theFile1.FileName)
  thePath = Server.MapPath("write/") + thePath
  theFile1.SaveAs(thePath)
End If

theFile2 = Request.Files("image2")
If theFile2.ContentLength > 0 Then
  thePath = System.IO.Path.GetFileName(theFile2.FileName)
  thePath = Server.MapPath("write/") + thePath
  theFile2.SaveAs(thePath)
End If
%>

<html>
<body>
Images uploaded...
</body>
</html>


Upload to File Server Example

Upload to File Server

This example shows how to upload a file to a file server preserving any Macintosh or Unicode attributes of the original file. It assumes that minimal configuration settings in the web.config file are implemented.
HTML
sfmupload.htm

Our multipart HTML form contains one file field for upload. This page then submits data to sfmupload.aspx.

<html>
<body>
<form method="post" action="sfmupload.aspx" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" name="submit" value="submit">
</form>
<body>
</html>
ASP
sfmupload.aspx

We create an Upload object, and if a file has been uploaded, save it to a location. ABCUpload will automatically detect that we're specifying the destination location using a URL and will place the file appropriately. Here we use the WinSafeFileName to name the file - this is a Windows safe version of the original file name in Unicode format.

If the file came from a Macintosh the WinSafeFileName will contain the name of the file converted into the format used by Services for Macintosh (SFM). If the file was uploaded by Internet Explorer and is saved to a SFM volume Macintosh users will see a file identical to the original uploaded file with both resource and data forks intact.

[C#]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<html>
<body>
<%

Upload theUpload = new Upload();
UploadedFile theFile = theUpload.Files["file"];

if (theFile.Exists) {
  theFile.SaveSFM("write/" + theFile.WinSafeFileName);
  Response.Write("File uploaded...");
}
else {
  Response.Write("No file uploaded...");
}

%>
</body>
</html>

[VB]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<html>
<body>
<%

Dim theUpload As Upload = New Upload()
Dim theFile As UploadedFile = theUpload.Files("file")

If theFile.Exists = True Then
  theFile.SaveSFM("write/" + theFile.WinSafeFileName)
  Response.Write("File uploaded...")
Else
  Response.Write("No file uploaded...")
End If

%>
</body>
</html>


Pure HTML Progress Bar Upload Example

Pure HTML Progress Bar

This example shows how to show a Pure HTML Progress Bar during an upload. It assumes that minimal configuration settings in the web.config file are implemented.
ASP
progressupload.aspx

Our multipart HTML form contains one file field for upload and one text field.

The form action takes a URL which contains a Unique ID used to identify the transfer. It is this ID which allows the progress bar to connect with the uploading page.

When the form is submitted we will need to submit both the data in the main window and also spawn off a separate window to track progress. So instead of using a standard submit button we use a normal button with a client side JavaScript attached to it.

When the submit button is clicked the DoUpload client side function takes over. Before it allows the form to be submitted it takes the Unique ID - used to identify the transfer - and spawns a progress window (progressbar.aspx) putting the ID into the URL so that it can be picked up later.

This is an unusual use of HTTP and worth reiterating. The progressbar.aspx page has an ID supplied to it via the URL (i.e. a GET request). The progressupload.aspx page has the content of the form submitted to it via a standard POST and also has an ID supplied via the URL.

[C#]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>
<HTML>
<body>

  <script language="javascript">
  <!--
  function DoUpload(inUniqueID) {
    theFeats = "height=160,width=600,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no";
    window.open("progressbar.aspx?ProgressID=" + inUniqueID, inUniqueID, theFeats);
    document.myform.submit();
  }
  //-->
  </script>

  <% int theID = Progress.UniqueID(); %>
  <form name="myform" method="post" enctype="multipart/form-data" action="progressupload.aspx?UploadID=<% = theID %>">
  <input type="file" name="filefield1"><br><br>
  <input type="text" name="textfield1" value="some text"><br><br>
  <input type="button" name="dosubmit" value="Upload" OnClick="DoUpload(<% = theID %>)"><br>
  </form>

[VB]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>
<HTML>
<body>

  <script language="javascript">
  <!--
  function DoUpload(inUniqueID) {
    theFeats = "height=160,width=600,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no";
    window.open("progressbar.aspx?ProgressID=" + inUniqueID, inUniqueID, theFeats);
    document.myform.submit();
  }
  //-->
  </script>

  <% Dim theID As Integer = Progress.UniqueID() %>
  <form name="myform" method="post" enctype="multipart/form-data" action="progressupload.aspx?UploadID=<% = theID %>">
  <input type="file" name="filefield1"><br><br>
  <input type="text" name="textfield1" value="some text"><br><br>
  <input type="button" name="dosubmit" value="Upload" OnClick="DoUpload(<% = theID %>)"><br>
  </form>

For the upload processing section we'll make use of some advanced ABCUpload features designed for the efficient processing of very large uploads.

We start by creating an Upload object and check that we've received an uploaded file. If there's no file the most likely cause is that the client is requesting the form rather than uploading a file.

If we have a file we check to see if the file data has been cached as a temporary file. This type of caching will only occur if the GigUpload functionality is enabled.

If the file has been cached and it's not in an encoded format we detach it from the upload and move it wherever we want it to go. This avoids having two copies of a file on disk and it is also much faster if you are dealing with very large files.

If the file hasn't been cached or it's in an encoded format we use the SaveAs method to save the file to disk. This will be less efficient than a move operation if the uploaded data is many hundreds of MB in size.

Finally we report the file name using the properties associated with the Upload object and we report the contents of our text field using the standard ASP.NET Form collection.

[C#]
<%

Upload theUpload = new Upload();
UploadedFile theFile = theUpload.Files["filefield1"];
if ((theFile != null) && (theFile.ContentLength > 0)) {
  if ((theFile.TempFile == "") || (theFile.MacBinary == true)) // save using URL
    theFile.SaveAs("write/" + theFile.WinSafeFileName);
  else { // faster to move than copy
    string thePath = Server.MapPath("write/") + theFile.WinSafeFileName;
    if (System.IO.File.Exists(thePath))
      System.IO.File.Delete(thePath);
    System.IO.File.Move(theFile.Detach(), thePath);
  }

  // Say what was in the form.
  // Note the simultaneous use of both the ABCUpload upload
  // objects and of the built-in ASP.NET Request.Form collection.
  Response.Write("<H1>Upload Complete...</H1>");
  if (theFile != null)
    Response.Write("<P>File Name: " + theFile.WinSafeFileName + "</P>");
  Response.Write("<P>Field Content: " + Request.Form["textfield1"] + "</P>");
}

%>
</body>
</HTML>

[VB]
<%

Dim theUpload As Upload = New Upload()
Dim theFile As UploadedFile = theUpload.Files("filefield1")
Dim theLength As Long = 0
If (Not theFile Is Nothing) Then theLength = theFile.ContentLength
If (theLength > 0) Then
  If (theFile.TempFile = "") Or (theFile.MacBinary = True) Then ' save using URL
    theFile.SaveAs("write/" + theFile.WinSafeFileName)
  Else ' faster to move than copy
    Dim thePath As String = Server.MapPath("write/") + theFile.WinSafeFileName
    If System.IO.File.Exists(thePath) Then
      System.IO.File.Delete(thePath)
    End If
    System.IO.File.Move(theFile.Detach(), thePath)
  End If

  ' Say what was in the form.
  ' Note the simultaneous use of both the ABCUpload upload
  ' objects and of the built-in ASP.NET Request.Form collection.
  Response.Write("<H1>Upload Complete...</H1>")
  If (Not theFile Is Nothing) Then
    Response.Write("<P>File Name: " + theFile.WinSafeFileName + "</P>")
  End If
  Response.Write("<P>Field Content: " + Request.Form("textfield1") + "</P>")
End If

%>
</body>
</HTML>
ASP
progressbar.aspx

The progress bar is slightly more complicated. We insert meta-tags to ensure that it refreshes itself every couple of seconds. We create a Progress object and set the ID to the Unique ID we were passed in the URL. This synchronizes the Progress object with the matching upload.

We want to close the progress window once the transfer has been completed so we put in a simple piece of client side JavaScript to do this. The rest of the form simply reports to the user the information retrieved via the Progress object. The progress bar itself is simply a table containing a colored cell of a particular width.

[C#]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<%

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();
string theMeta = "<meta http-equiv=\"refresh\" content=\"2,progressbar.aspx?ProgressID=" + theID + "\">";
string thePercent = theProgress.PercentDone.ToString();
string theKbps = 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();
string theNote = theProgress.Note;
string theFileName = theProgress.FileName;
if (theProgress.Finished) theMeta = "";

%>
<HTML>
<HEAD>
<title>Progress...</title>
<meta http-equiv="expires" content="Tue, 01 Jan 1981 01:00:00 GMT">
<% = theMeta %>
<script language="javascript">
<!--
if (<% = thePercent %> >= 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="<% = thePercent %>%" 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 time left:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">
<% = theMins %> min
<% = theSecs %> secs
(<% = theKbdone %> KB of
<% = theKbtotal %> KB uploaded)
</font></td>
</tr>
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"> Transfer Rate:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><% = theKbps %> 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"><% = theNote %></font></td>
</tr>
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Uploading File:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><% = theFileName %></font></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr>
</table>
</body>
</HTML>

[VB]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<%

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()
Dim theMeta As String = "<meta http-equiv=""refresh"" content=""2,progressbar.aspx?ProgressID=" + theID + """>"
Dim thePercent As String = theProgress.PercentDone.ToString()
Dim theKbps As String = Math.Round(theProgress.BytesPerSecondCurrent / 1024,1).ToString()
Dim theKbdone As String = Math.Round(CType(theProgress.BytesDone / 1024, Double), 1).ToString()
Dim theKbtotal As String = Math.Round(CType(theProgress.BytesTotal / 1024, Double), 1).ToString()
Dim theNote As String = theProgress.Note
Dim theFileName As String = theProgress.FileName
If theProgress.Finished= True Then theMeta = ""

%>
<HTML>
<HEAD>
<title>Progress...</title>
<meta http-equiv="expires" content="Tue, 01 Jan 1981 01:00:00 GMT">
<% = theMeta %>
<script language="javascript">
<!--
if (<% = thePercent %> >= 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="<% = thePercent %>%" 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 time left:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">
<% = theMins %> min
<% = theSecs %> secs
(<% = theKbdone %> KB of
<% = theKbtotal %> KB uploaded)
</font></td>
</tr>
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"> Transfer Rate:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><% = theKbps %> 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"><% = theNote %></font></td>
</tr>
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Uploading File:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><% = theFileName %></font></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr>
</table>
</body>
</HTML>
ASP
global.asax

In some situations you may wish to pick up progress events from within a global.asax file.

The progress database is stored in Application Scope and if your progress bar and upload page are being served from different web applications they may become disassociated from each other. This is not a normal situation but it can occur for some web site designs.

The most common situation in which this may occur is when operating from a web farm. In this scenario a page may be served from any one of a number of machines. So your upload page may be processed by one server while your progress bar is being served from another.

In this situation you may wish to store the upload state in an external store such as a database. This way you can code your progress bar to retrieve upload state from your shared store rather than from the standard Progress object.

In order to do this you need to pick up the progress update events which are sent out by ABCUpload and use them to update your shared store. You can do this using a handler within the global.asax file.

The particular form of shared store you want to use dictates how your code should be written. The example below is an illustrative example designed to show how a handler can be coded. It simply makes a log of all the progress events which are received.

[C#]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<script language="C#" runat="server">

public void Progress_UpdateProgress(object source, EventArgs e) {
  // this is an inefficient implementation but it illustrates how progress events can be captured
  // needless to say you should delete this handler or disable this logging for any live application
  string path = Server.MapPath("write/progress_log.txt");
  Progress state = ((ProgressEventArgs)e).State;
  System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true);
  sw.BaseStream.Seek(0, System.IO.SeekOrigin.End);
  sw.WriteLine(state.ID.ToString() + " " + state.Note + " " + state.BytesDone.ToString() + " of " + state.BytesTotal.ToString());
  sw.Close();
}

</script>

[VB]
<%@ Import Namespace="WebSupergoo.ABCUpload6" %>

<script language="VB" runat="server">

Public Sub Progress_UpdateProgress(ByVal source As Object, ByVal e As EventArgs)
  ' this is an inefficient implementation but it illustrates how progress events can be captured
  ' needless to say you should delete this handler or disable this logging for any live application
  Dim path As String = Server.MapPath("write/progress_log.txt")
  Dim state As Progress = (CType(e, ProgressEventArgs)).State
  Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(path,True)
  sw.BaseStream.Seek(0, System.IO.SeekOrigin.End)
  sw.WriteLine(state.ID.ToString() + " " + state.Note + " " + state.BytesDone.ToString() + " of " + state.BytesTotal.ToString())
  sw.Close()
End Sub

</script>


Codebehind Upload

Codebehind Progress Bar

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.


Upload Class

This class encapsulates a file upload. It is designed to supplement the functionality of the Files collection in the standard HttpRequest object. The Files collection in this class behaves identically to the Files collection in the HttpRequest object.

Although you can use the HttpRequest Files collection to access uploaded files it is better to create and use an Upload object. The Upload object automatically manages and decodes uploaded files to allow you to deal with the functionality of your application rather than housekeeping issues.

Inherits From: Object
Namespace: WebSupergoo.ABCUpload6
Assembly: ABCUpload6.DLL

Method | Description
Upload | Upload class constructor.
Dispose | Clears the upload and releases all held resources.
Save | Saves a dump of the raw uploaded data.

Property | Description
CodePage | Gets or sets the CodePage to use when interpreting uploaded text and attributes.
Context | Gets or sets the HttpContext for this upload.
Files | Gets the UploadedFileCollection containing all the files in the upload.
Overwrite | Gets or sets a value indicating whether existing files should be overwritten using save operations.


Upload Constructor

Upload class constructor.
Syntax

Upload()
Notes

Initializes a new instance of the Upload class.
See Also

None.


Dispose Method

Clears the upload and releases all held resources.

Syntax

void Dispose()
Notes

This method clears all memory and deletes any resources such as temporary files held by the upload object. You should not use the upload object after calling this method.

You do not have to call this method as resources will automatically be reclaimed by the garbage collector once the upload object goes out of scope. However you may want to explicitly delete all held resources to ensure timely disposal.
See Also

None.


Save Method

Saves a dump of the raw uploaded data.

Syntax

void Save(string path)
Params
Name | Type | Description
path | string | The path to the save destination.
Notes

You are only likely to use this method for debugging. It allows you to save out the raw data as uploaded by the browser. You can then recreate the upload at a later date complete with all files and form contents intact. For details of how to load up a saved dump file see the Recreating Uploads section of this document.

Whether the path is treated as a virtual path or an absolute path is determined by the standard ABCUpload path interpretation algorithm.

Whether other files are automatically overwritten is determined by the Overwrite property.
See Also

Recreating Uploads discussion. Path Interpretation discussion. Overwrite property.


CodePage Property

Type | Default Value | Description
int | The current HttpContext code page. | Gets or sets the CodePage to use when interpreting uploaded text and attributes.
Notes

Some browsers do not support Unicode and instead upload raw Multibyte Character Set (MBCS) text. In these cases ABCUpload interprets text such as file names in the context of the current code page.

For example if you are expecting uploads to be coming from Korean clients you might set the CodePage property to the Korean CodePage ID (949). For Japanese you might use the Japanese CodePage (932).

As you change this property the interpretation of MBCS text will change dynamically.
See Also

UploadedFile.FileName property. UploadedFile.Text property.


Context Property

Type | Default Value | Description
HttpContext | The current HttpContext. | Gets or sets the HttpContext for this upload.
Notes

Every request is interpreted within a context called the HttpContext. When you first create an Upload object the current HttpContext is used as the default value. You can access or change this default using the Context property.
See Also

None.


Files Property

Type | Default Value | Description
PostedFileCollection | All uploaded files. | Gets the UploadedFileCollection containing all the files in the upload.
Notes

The Files collection in the Upload object parallels the Files collection within the HttpRequest object. Both contain a collection of uploaded files which can be referenced either by field name or by index number.
See Also

UploadedFileCollection class.


Overwrite Property

Type | Default Value | Description
bool | true | Gets or sets a value indicating whether existing files should be overwritten using save operations.
Notes

For safety reasons you can stop saved files overwriting existing files.

If you do not wish to overwrite files you must change the Overwrite property to be false. If you then try to save a file to a location which already contains an existing file an Exception will be raised.
See Also

Save method. UploadedFile.SaveAs method. UploadedFile.SaveSFM method.


UploadedFileCollection Class

This class encapsulates all the files within a file upload. It is designed to mimic the functionality of the HttpFileCollection you would normally obtain from the HttpRequest class.

You cannot create an UploadedFileCollection object directly. You must obtain it from the Files property of an Upload object.

Inherits From: NameObjectCollectionBase
Namespace: WebSupergoo.ABCUpload6
Assembly: ABCUpload6.DLL

Method | Description
GetKey | Returns the name of the UploadedFileCollection member with the specified numerical index.

Property | Description
AllKeys | Gets a string array containing the keys (names) of all members in the file collection.
Item | Gets an individual UploadedFile object from the file collection.


GetKey Method

Returns the name of the UploadedFileCollection member with the specified numerical index.
Syntax

void GetKey(int index)
Params
Name | Type | Description
index | int | The index of the object name to be returned.
Notes

This method allows you to find key names given only a numerical index. For example you might want to know what the field name was for the second uploaded file. Calling this method and passing in the value two as the index would return the field name.
See Also

None.


AllKeys Property

Type | Default Value | Description
string[] | All the keys in the collection. | Gets a string array containing the keys (names) of all members in the file collection.
Notes

You may wish to obtain a list of all the field names in the collection so that you can perform an operation on each of them. This property contains such a collection.
See Also

None.


Item Property

Type | Default Value | Description
UploadedFile | N/A | Gets an individual UploadedFile object from the file collection.
Notes

Gets an individual UploadedFile object from the file collection. This property is overloaded to allow retrieval of objects by either name (string) or numerical index (int).
See Also

UploadedFile class.


UploadedFile Class

This class encapsulates an uploaded file. It is designed to supplement the functionality of the HttpPostedFile class. As such an UploadedFile object behaves very similarly to an HttpPostedFile object.

While this class provides the same basic methods and properties as the HttpPostedFile object it supplements them with other methods and properties for a greater level of control over the upload process.

You cannot create an UploadedFile object directly. You must obtain it by referencing an item within the Files property of an Upload object.

Inherits From: Object
Namespace: WebSupergoo.ABCUpload6
Assembly: ABCUpload6.DLL

Method | Description
Detach | Detaches any temporary file associated with the uploaded file.
SaveAs | Saves an uploaded file onto the server.
SaveSFM | Saves an uploaded file onto the server using Services for Macintosh (SFM) format if appropriate.

Property | Description
ContentLength | Gets the size in bytes of the uploaded file data.
ContentType | Gets the MIME content type of a file sent by a client.
DataStream | Gets a Stream object which allows access to the data within the uploaded file data.
Exists | Gets a value indicating whether a file was uploaded or not.
Extension | Gets the file name extension that should be associated with this file.
FileName | Gets the path to the file on the client's machine.
InputStream | Gets a Stream object which allows access to the data within the uploaded file.
MacBinary | Gets a value indicating whether the raw upload data was encoded in MacBinary.
RawFileName | Gets the name of the file on the client's machine as raw data.
RawStream | Gets a Stream object which allows access to the raw upload data.
RezStream | Gets a Stream object which allows access to the resource fork (if any) within the uploaded file.
TempFile | Gets the path to any temporary file associated with the upload.
Text | Gets the text contained within an uploaded file as a string.
URLSafeFileName | Gets the name of the file on the client's machine in a URL safe format.
WinSafeFileName | Gets the name of the file on the client's machine in a Windows safe format.


Detach Method

Detaches any temporary file associated with the uploaded file.
Syntax

string Detach()
Params
Name | Type | Description
return | string | The path to the temporary file which was detached.
Notes

When using GigUpload the contents of each posted file are cached on disk rather than in memory. You can continue to use the standard methods you would use for smaller files but you may find it more efficient to access the uploaded file directly.

This is particularly true for very large uploads. It can take some time to copy a 1 GB file from one location to another and often it is more efficient simply to detach the upload cache, move it to the required location and then rename it.

When you detach a temporary file the path to that file will be passed back to you. At that point you take responsibility for the file and you should ensure that it is either moved to an appropriate location or deleted as appropriate.
See Also

GigUpload technology. ABCUpload Config files. TempFile property.


SaveAs Method

Saves an uploaded file onto the server.
Syntax

void SaveAs(string path)
Params
Name | Type | Description
path | string | The path to the save destination.
Notes

This method allows you to save an uploaded file to a location in your web site or on your disk. All you need to do is to specify a valid path.

If you use the SaveAs method and no file has been uploaded a zero length file will be saved. To avoid saving zero length files check the Exists property before using the SaveAs method.

Whether the path is treated as a virtual path or an absolute path is determined by the standard ABCUpload path interpretation algorithm.

Whether other files are automatically overwritten is determined by the Upload Overwrite property.
See Also

Path Interpretation discussion. SaveSFM method. Exists property. MacBinary property. Upload.Overwrite property.


SaveSFM Method

Saves an uploaded file onto the server using Services for Macintosh (SFM) format if appropriate.
Syntax

void SaveSFM(string path)
Params
Name | Type | Description
path | string | The path to the save destination.
Notes

This method behaves very similarly to the SaveAs method but it ensures that MacBinary format files are saved in Services For Macintosh (SFM) format. This method uses an unmanaged call to the Windows API so you must ensure that you have permission to call unmanaged code.

If you save to an NTFS volume and the upload was in MacBinary format then the the complete file will be saved with data fork, resource fork and other file information completely intact. Windows users will see only the data fork but Macintosh users accessing the volume using Services for Macintosh (SFM) will see the complete file as uploaded from the client browser.

If you wish to maintain the Macintosh filename you should save the file using the WinSafeFileName as a base filename.

Whether the path is treated as a virtual path or an absolute path is determined by the standard ABCUpload path interpretation algorithm.

Whether other files are automatically overwritten is determined by the Upload Overwrite property.
See Also

Path Interpretation discussion. SaveAs method. Exists property. MacBinary property. Upload.Overwrite property.


ContentLength Property

Type | Default Value | Description
long | Dependent on uploaded file. | Gets the size in bytes of the uploaded file data.
Notes

This is the size of the data held in the field. If the field contains an uploaded file the size is the same as the size of the uploaded file. The size is measured in bytes and will be equal to zero if no data is present.

If the uploaded file was encoded in MacBinary this refers to the length of the data fork only.

This property is equivalent to the HttpPostedFile ContentLength property.

See Also

InputStream property.


ContentType Property

Type | Default Value | Description
string | Dependent on uploaded file. | Gets the MIME content type of a file sent by a client.
Notes

This contains the MIME type of the uploaded file as reported by the uploading browser. This MIME type is not reliable as different Browsers on different Operating Systems may report different MIME types for the same file. Treat with caution.

This property is equivalent to the HttpPostedFile ContentType property.

See Also

None.


DataStream Property

Type | Default Value | Description
Stream | Dependent on uploaded file. | Gets a Stream object which allows access to the data within the uploaded file data.
Notes

This contains the data within the uploaded file.

For most uploads the contents of this stream will be identical to the contents of the stream obtained from the RawStream property. However if files have been uploaded from MacBinary capable Macintosh browsers (Internet Explorer but not Netscape Navigator) this property will contain only the uploaded data fork of the file.
See Also

MacBinary property. RezStream property. RawStream property.


Exists Property

Type | Default Value | Description
bool | Dependent on uploaded file. | Gets a value indicating whether a file was uploaded or not.
Notes

If the field is a file upload field and a file was uploaded then this property will be true. If not it will be false.
See Also

None.


Extension Property

Type | Default Value | Description
string | Dependent on uploaded file. | Gets the file name extension that should be associated with this file.
Notes

This contains the file name extension of the file uploaded. If a file name extension is not available it may be derived from other information.

The returned value includes the period character of the extension, such as ".jpg" or ".txt".

Not all platforms use file name extensions so in these cases other information may be used to identify the type of file.

If files are uploaded from MacBinary capable Macintosh browsers (Internet Explorer but not Netscape Navigator) the upload contains information on the Macintosh Creator and Type. This information may be used to infer the file type of the uploaded document. The inference is based firstly on the Services for Macintosh (SFM) settings which can be altered using MacFile. If SFM is not installed or does not provide a suitable match then a heuristic approach is used.

In some cases no file type information will be available. In these cases an empty string will be returned.

See Also

MacBinary property.


FileName Property

Type | Default Value | Description
string | Dependent on uploaded file. | Gets the path to the file on the client's machine.
Notes

This contains the file path as reported by the uploading client browser. This is typically the path to the file as exists on the client computer.

  • Windows Browsers upload a path name - e.g. "c:\mydirectory\myfile.ext"
  • Macintosh Browsers upload the file name only - e.g. "Picture of Mum?"
  • UNIX users upload a path name - e.g. "mydrive:\mydir\\myfile.ext"

This property may contain Unicode characters depending on the locale of the uploading operating system, the name of the file and the type of browser being used to perform the upload. In general Internet Explorer browsers support Unicode uploads while Netscape Navigator browsers do not.

The FileName is interpreted in the context of the current code page, taking into account browser specific state information. For this reason it will return correct file names in cases where ASP.NET often returns incorrect ones.

Depending on the source Operating System and Browser this name may contain characters such as question marks and slashes which are illegal in file names on Windows.

This property is equivalent to the HttpPostedFile FileName property.

See Also

RawFileName property. WinSafeFileName property. URLSafeFileName property. Upload.CodePage property.


InputStream Property

Type | Default Value | Description
Stream | Dependent on uploaded file. | Gets a Stream object which allows access to the data within the uploaded file.
Notes

This contains the data within the uploaded file. This data is identical to the data within the DataStream property.

This property is equivalent to the HttpPostedFile InputStream property.

See Also

DataStream property.


MacBinary Property

Type | Default Value | Description
bool | Dependent on uploaded file. | Gets a value indicating whether the raw upload data was encoded in MacBinary.
Notes

This property is true if the raw data of the upload field contains a valid MacBinary encoding.

Macintosh files are different from Windows or UNIX files in a number of ways. Firstly every file consists of two separate streams or forks. The data fork holds the basic file information that you would find in a Windows file. The resource fork contains a small database of other associated information such as picture previews, notes and icons. So a BMP image might contain the BMP in the data fork and a icon, preview and copyright note in the resource fork. Secondly Macintosh files do not contain a file type extension - instead they have a hidden type and creator code.

When Internet Explorer uploads a file from a Macintosh it puts all this information together into one stream encoded as MacBinary. At a basic level ABCUpload uses the creator and type properties to infer the file type. However Microsoft has given us the ability to handle this kind of file completely correctly and so this is what we do.

Using ABCUpload you can save a MacBinary file to an NTFS formatted disk maintaining complete integrity of data fork, resource fork, file type and creator. This gives you the best of both worlds. If you look at such a file from Windows it will look like a standard file (e.g. JPG, DOC etc.) but if you serve this file to Macintosh users using Services for Macintosh (SFM) they will see the original Macintosh file completely intact. Through named stream support available on NTFS the data fork, resource fork and other information is maintained as a package and moves with the file.
See Also

DataStream property. RezStream property. RawStream property. SaveSFM method.


RawFileName Property

Type | Default Value | Description
byte[] | Dependent on uploaded file. | Gets the name of the file on the client's machine as raw data.
Notes

This property contains the raw file path data as reported by the uploading client browser. This is typically the path to the file as exists on the client computer.

The FileName property is derived from the RawFileName in the context of the current code page, taking into account browser specific state information.

You are unlikely to need to access this property unless you are doing custom conversion of file names using different character sets.

See Also

FileName property. Upload.CodePage property.


RawStream Property

Type | Default Value | Description
Stream | Dependent on uploaded file. | Gets a Stream object which allows access to the raw upload data.
Notes

This contains the raw binary data uploaded by the client browser. It may be encoded in a format such as MacBinary which is why it is not generally useful.

If the upload was not encoded in MacBinary the RawStream will contain the same data as that obtained from the DataStream.
See Also

MacBinary property. DataStream property. RezStream property.


RezStream Property

Type | Default Value | Description
Stream | Dependent on uploaded file. | Gets a Stream object which allows access to the resource fork (if any) within the uploaded file.
Notes

This contains the resource fork of the uploaded file.

If the upload was not encoded in MacBinary this property will contain a zero length stream.
See Also

MacBinary property. DataStream property. RawStream property.


TempFile Property

Type | Default Value | Description
string | Dependent on configuration. | Gets the path to any temporary file associated with the upload.
Notes

When using GigUpload the contents of each posted file are cached on disk rather than in memory. You can continue to use the standard methods you would use for smaller files but you may find it more efficient to access the uploaded file directly.

This property contains the path to any temporary file. Note that ownership of the file is retained by the upload unless you call the Detach method.
See Also

GigUpload technology. ABCUpload Config files. Detach method.


Text Property

Type | Default Value | Description
string | Dependent on uploaded file. | Gets the text contained within an uploaded file as a string.
Notes

This contains the content of the uploaded field as a string.

If the field was a file upload field this property will contain the content of the uploaded file as a string. If the uploaded file was encoded in MacBinary it will contain the data fork only.

See Also

MacBinary property.


URLSafeFileName Property

Type | Default Value | Description
string | Dependent on uploaded file. | Gets the name of the file on the client's machine in a URL safe format.
Notes

This contains the name of the uploaded file translated into a format that can be used in a URL.

This property contains a file name rather than a file path. This means that it contains no directory information. Typical values might be "my_file.htm", "my_picture.jpg" or "my_note.txt".

This property contains only lower case alphanumeric characters and minimal punctuation such as period, dash and underscore characters.

See Also

FileName property. WinSafeFileName property.


WinSafeFileName Property

Type | Default Value | Description
string | Dependent on uploaded file. | Gets the name of the file on the client's machine in a Windows safe format.
Notes

This contains the name of the uploaded file translated into a format that can be used to save the file.

This property contains a file name rather than a file path. This means that it contains no directory information. Typical values might be "My File.htm", "My Picture.jpg" or "Bits&Pieces.txt".

In general you should only use the WinSafeFileName for saving the file when the original name is essential to the upload. In other cases you should assign a new name to your file to allow you to maintain control over the names of files saved on your server. If you require a unique name for every file you may wish to use the System.Guid static methods for generating Unique IDs.

Note that the fact that the file name is safe for saving does not mean that it is safe to use in a URL. For instance it may contain spaces or Unicode characters. If you need a URL safe name you should use the URLSafeFileName property.

If files containing illegal characters are uploaded from Macintosh browsers the names will be translated into the standard Services for Macintosh (SFM) Unicode format so that they can be saved intact. To a Windows user the file may appear to contain unusual characters but to a Macintosh user the name will appear as it was when uploaded.

In other cases when uploaded file names contain illegal characters these are deleted so that the file name can be used as part of a save name.

See Also

SaveSFM method. FileName property. URLSafeFileName property.


Progress Class

This class allows access to the central upload database. Each upload passing through the Progress Module has a Unique ID and an entry in the upload database. If you know the ID of an upload you can create a synchronized Progress object and so obtain information on the current status.

Inherits From: Object
Namespace: WebSupergoo.ABCUpload6
Assembly: ABCUpload6.DLL

Method | Description
Progress | Progress class constructor (overloaded).

Property | Description
BytesDone | Gets the number of bytes uploaded so far.
BytesPerSecondAverage | Gets the average data transfer rate for the upload in bytes per second.
BytesPerSecondCurrent | Gets the current data transfer rate for the upload in bytes per second.
BytesTotal | Gets the total upload size in bytes.
CodePage | Gets or sets the CodePage to use when interpreting the current file name.
ElapsedSeconds | Gets the total number of seconds elapsed since the start of the upload.
FileName | Gets the name of the file currently being uploaded.
Finished | Gets a value that indicates whether data transfer is finished or not.
ID | Gets or sets the ID for the upload.
static» IDs | Gets an array of all current upload IDs.
Note | Gets or sets the current status of the upload.
PercentDone | Gets the percent of the upload that has been completed.
SecondsLeft | Gets the estimated number of seconds left for the transfer to complete.
Started | Gets a value that indicates whether data transfer has started or not.


Progress Constructor

Upload class constructor (overloaded).
Syntax

Upload(int id)
Upload(string id)

Notes

Initializes a new instance of the Progress class setting the ID to the appropriate value as indicated by the number or string passed to the constructor.

IDs must be numeric so if a string is passed in it will be converted to an integer. If it is not possible to convert the string to an integer then the ID will default to zero.
See Also

ID property.


BytesDone Property

Type | Default Value | Description
int | 0 | Gets the number of bytes uploaded so far.
Notes

The number of bytes uploaded so far.
See Also

BytesTotal property.


BytesPerSecondAverage Property

Type | Default Value | Description
double | 0.0 | Gets the average data transfer rate for the upload in bytes per second.
Notes

The average data transfer rate for the upload in bytes per second
See Also

BytesPerSecondCurrent property.


BytesPerSecondCurrent Property

Type | Default Value | Description
double | 0.0 | Gets the current data transfer rate for the upload in bytes per second.
Notes

The current data transfer rate for the upload in bytes per second.
See Also

BytesPerSecondAverage property.


BytesTotal Property

Type | Default Value | Description
int | 0 | Gets the total upload size in bytes.
Notes

The total number of bytes to be uploaded.

This value has to be transmitted from the client browser to the server and so is not immediately available. During this connecting period the value will default to zero.
See Also

BytesDone property.


CodePage Property

Type | Default Value | Description
int | The current HttpContext code page. | Gets or sets the CodePage to use when interpreting the current file name.
Notes

Some browsers do not support Unicode and instead upload raw Multibyte Character Set (MBCS) text. In these cases ABCUpload interprets text such as file names in the context of the current code page.

As you change this property the interpretation of the file name will change dynamically.
See Also

FileName property. Upload.CodePage property.


ElapsedSeconds Property

Type | Default Value | Description
double | 0.0 | Gets the total number of seconds elapsed since the start of the upload.
Notes

The number of seconds that the transfer has been in progress.
See Also

SecondsLeft property.


FileName Property

Type | Default Value | Description
string | "" | Gets the name of the file currently being uploaded.
Notes

This contains the file path as reported by the uploading client browser. This is equivalent to the path in the FileName property of the UploadedFile object.

The FileName is interpreted in the context of the current code page, taking into account browser specific state information.

See Also

UploadedFile.FileName property.


Finished Property

Type | Default Value | Description
bool | false | Gets a value that indicates whether data transfer has finished or not.
Notes

This value reflects whether the transfer has finished. The transfer is regarded as finished when data transfer stops and all data has been processed.
See Also

Started property.


ID Property

Type | Default Value | Description
int | 0 | Gets or sets the ID for the upload.
Notes

Every upload which passes through the Progress Module is assigned a unique ID to allow other dependent objects such as the Progress object to keep track of it.

The Progress ID is generally assigned when you first create a Progress object but you can access and change it at a later date using this property.
See Also

IDs property.


IDs Property

Type | Default Value | Description
int[] | Dependent on the current upload status. | Gets an array of all current upload IDs.
Notes

Use this static property to get an array of all current upload IDs.

As uploads are registered in the upload database the ID of each will be added to this array. Entries in the database do not expire immediately after a transfer is complete - instead the database is periodically purged to remove old upload entries.
See Also

ID property.


Note Property

Type | Default Value | Description
string | "" | Gets or sets the current status of the upload.
Notes

The note property is typically used to pass information from the upload to the Progress object. It will be updated as the status of the transfer changes.

You can change this property if you want to pass messages between Progress objects.

See Also

ABCUpload Config files.


PercentDone Property

Type | Default Value | Description
double | 0.0 | Gets the percent of the upload that has been completed.
Notes

This value reflects the percentage of the transfer that has taken place.

There are overheads associated with initiating and processing an upload so although this property is indicative of the proportion of data transferred it is not a direct reflection of it.
See Also

None.


SecondsLeft Property

Type | Default Value | Description
double | 0.0 | Gets the estimated number of seconds left for the transfer to complete.
Notes

This value reflects the estimated number of seconds of transfer left. It is based on the amount of data transferred and the average data transfer rate. Because data transfer rates may vary the SecondsLeft property is an estimate - it may increase or decrease as network conditions change.

See Also

ElapsedSeconds property.


Started Property

Type | Default Value | Description
bool | false | Gets a value that indicates whether data transfer has started or not.
Notes

This value reflects whether the transfer has started. The transfer is regarded as started when the upload interceptor first updates the central upload database.
See Also

Finished property.


Registration Class

If you are building an installer which incorporates ABCUpload this class allows you to install and register the library automatically. It also allows you access to registration information about the installation.

Inherits From: Object
Namespace: WebSupergoo.ABCUpload6
Assembly: ABCUpload6.DLL

Method | Description
static» Install | Installs all necessary resources for ABCUpload to function.
static» Uninstall | Uninstalls installed resources.

Property | Description
static» License | Gets the current license description.
static» Serial | Gets or sets the serial key.
static» TrialKey | Gets a trial key.


Install Method

Installs all necessary resources for ABCUpload to function.
Syntax

void Install()
Notes

This function writes values to the registry so you must be logged on with full access rights when you call this function.

On successful installation a success event will be written to the Application Event Log.
See Also

Uninstall method.


Uninstall Method

Uninstalls installed resources.

Syntax

void Uninstall()
Notes

This method uninstalls resources installed by the Install function.
See Also

Install method.


License Property

Type | Default Value | Description
string | Depends on installation. | Gets the current license description.
Notes

This property contains the license description in human readable format. For example:

Trial License - 23 days 22:48:02 Left
See Also

None.


Serial Property

Type | Default Value | Description
string | "" | Gets or sets the serial key.
Notes

If you want to install a serial key you will normally do so using the ABCSettings control panel.

However if you wish to automate your install process you can install a serial key by inserting the key value into this property.

If a valid serial key is installed the value of this property will reflect the current key.

Setting this property may write values to the registry so you must be logged on with full access rights when you use it.
See Also

ABCUpload Config serial attribute.


TrialKey Property

Type | Default Value | Description
string | Depends on install. | Gets a trial key.
Notes

If you need to obtain a trial key you will normally do so using the ABCSettings control panel.

The trial key reflects the current trial license on your local computer. Under some circumstances you may wish to copy this trial license to a config file on a remote computer.

You will only need to install a trial license in the config file if you do not have the required permissions to run the ABCUpload installer. The trial key should be inserted into the config file serial attribute.
See Also

ABCUpload Config serial attribute.


Progress Class

ProgressEventArgs Class

This class is derived from the EventArgs class and encapsulates the current state of progress when a progress event is fired by ABCUpload.

Inherits From: EventArgs
Namespace: WebSupergoo.ABCUpload6
Assembly: ABCUpload6.DLL

Method | Description
None |

Property | Description
State | The progress object which has changed.


State Property

Type | Default Value | Description
Progress | N/A | The progress object which has changed.
Notes

This is the Progress object which has changed and triggered an update event.
See Also

None.