Upload Files with Your Browser in 2 Lines of Code

By Peter Persits

Copyright (c) 1998 Persits Software, Inc.

Introduction

File uploading is the process of sending an arbitrary file from a client machine to the server. The easiest and most convenient way to upload a file is to use an RFC1867-enabled browser such as Microsoft Internet Explorer 4.0+, Netscape 3.0+, or Internet Explorer 3.0 with the upload add-on. Browser-based uploading is performed via an HTML form with the attribute ENCTYPE="multipart/form-data". This form must also contain one or more <INPUT TYPE=FILE> items with which the user specifies local files to be uploaded.

The data posted by a form with the ENCTYPE="multipart/form-data" attribute must be parsed by a server-side process to extract the uploaded files and other non-file items. In the ASP environment, this task is best performed with a compiled active server component such as AspUpload from Persits Software, Inc (http://www.persits.com).

All samples in this article assume that AspUpload is installed on your system. Download your free evaluation copy of AspUpload from http://www.persits.com/aspupload.html. Unzip the archive file, put AspUpload.dll in any directory and at the MS DOS prompt execute the command
regsvr32 c:\dir\AspUpload.dll

Getting Started

Let's create a simple HTML form that will let us upload up to three files, and a script to handle the uploading.
This is out  first HTML file Test1.htm:

<HTML>
<BODY BGCOLOR="#FFFFFF">

<FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="UploadScript1.asp">
<INPUT TYPE=FILE SIZE=60 NAME="FILE1"><BR>
<INPUT TYPE=FILE SIZE=60 NAME="FILE2"><BR>
<INPUT TYPE=FILE SIZE=60 NAME="FILE3"><BR>
<INPUT TYPE=SUBMIT VALUE="Upload!">
</FORM>
</BODY>
</HTML>

Each <INPUT TYPE=FILE> item appears on the browser as a text input box with the button "Browse..." next to it. If you don't see the Browse button it most probably means that your browser does not support file uploading.

Here is the corresponding uploading script UploadScript1.asp:
 

<HTML> 
<BODY> 
<% 
Set Upload = Server.CreateObject("Persits.Upload.1") 
Count = Upload.Save("c:\upload")
%>

<% = Count %> files uploaded. 
</BODY> 
</HTML>

The first line of the ASP script simply creates an instance of the AspUpload object. The second line calls the Save method of the component which actually does the job: it parses the posting received from the browser, figures out how many files are being uploaded, and saves then in the specified directory on the server. The directory name may or may not be backslash terminated. All the files will be saved in that directory under their original names. We will see how to change any or all the file names shortly.

The Save method returns the number of files successfully uploaded. In case of an error this method will throw an exception.

Notice that you can use any or all of the three input boxes on our form. AspUpload is smart enough to figure out which input boxes are used and which are not
 

Using FILES and FORM Collections to Access Individual Form Items

Let's take a look at our second set of samples:

Test2.htm
<HTML>
<BODY BGCOLOR="#FFFFFF">

<FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="UploadScript2.asp">
File 1:<INPUT TYPE=FILE NAME="FILE1">
Description 1:<INPUT TYPE=TEXT NAME="DESCR1"><BR>

File 2:<INPUT TYPE=FILE NAME="FILE2">
Description 2:<INPUT TYPE=TEXT NAME="DESCR2"><BR>

<INPUT TYPE=SUBMIT VALUE="Upload!">

</FORM>
</BODY>
</HTML>
 
UploadScript2.asp
<HTML> 
<BODY> 
<% 
Set Upload = Server.CreateObject("Persits.Upload.1") 
Upload.Save "c:\upload"
%> 
Files:<BR> 
<% 
For Each File in Upload.Files 
Response.Write File.Name & "=" & File.Path & " (" & File.Size & ")<BR>"
Next
%> 

<P> 
Other items:<BR> 
<% 
For Each Item in Upload.Form 
Response.Write Item.Name & "=" & Item.Value & "<BR>"
Next
%> 
</BODY> 
</HTML>

Notice that our HTML form now has two kinds of input boxes, TYPE=FILE and TYPE=TEXT. Because of the ENCTYPE attribute of out form, we can no longer access the form variables via the standard ASP Response.Form collection. That's where the Upload.Form collection comes to the rescue. This collection is virtually identical to Response.Form, i.e. we can access its elements via integer or string indexes, for example:

Set Item1 = Upload.Form("DESCR1")

or

Set Item1 = Upload.Form(1).

We can also scroll through the items in the collection using the For-Each statement as shown in the code sample above. The Form collection contains objects of the type FormItem which only have two string properties, Name and Value (default property).

It's important to remember that the Upload.Form collection only includes non-file items, i.e. form items other than <INPUT TYPE=FILE>. AspUpload provides another collection, namely Files, to contain objects of the type UploadedFile which represent uploaded files that came from the <INPUT TYPE=FILE> items. Much like the Form collection, the Files collection items can be accessed using string or integer indexed, or via a For-Each statement, as shown in the example above.

After running Example 2, we will see something like this:

Files:
FILE1=c:\upload\File1.xls (108544)
FILE2=c:\upload\File2.zip (211687)

Other items:
DESCR1=bla bla
DESCR2=test test

Notice that we have obtained the destination paths and sizes of the uploaded files via the Path and Size properties of the UploadedFile object, respectively.

If our form only contained 1 file input box, say <INPUT TYPE=FILE NAME="ONLYFILE">, there would be no need to use a For-Each statement. We could simply say

Response.Write Upload.Files("ONLYFILE").Path

or, more generally,

Response.Write Upload.Files(1).Path

IMPORTANT: Neither the Files nor Form collections are populated until the Save method is called. It is therefore incorrect to refer to either of these collections before calling Upload.Save.

' Incorrect!
Upload.Save( Upload.Form("Path") )

Setting a Limit on File Size

Suppose you need to limit the size of the files being uploaded to prevent the congestion of your server's disk space. All you need to do is call the SetMaxSize method on your Upload object just before calling Save:

Set Upload = Server.CreateObject("Persits.Upload.1")
Upload.SetMaxSize 50000, False
Upload.Save "c:\upload"

In this example we are limiting the size of the uploaded files to 50000 bytes. The optional second parameter specifies whether a file bigger than the maximum should be truncated (if set to False or omitted), or rejected with an error exception (if set to True).
 

Forcing Unique File Names

By default, AspUpload will overwrite existing files in the upload directory. If this is undesirable, the component can be configured to generate unique names for the files being uploaded to prevent overwriting existing files in the upload directory. This is done by setting UploadManager's OverwriteFiles property to False before calling Save:

Upload.OverwriteFiles = False

This property is True by default.

To prevent name collisions, AspUpload will append the original file name with an integer number in parentheses. For example, if the file MyFile.txt already exists in the upload directory, and another file with the same name is being uploaded, AspUpload will save the new file under the name MyFile(1).txt. If we upload more copies of MyFile.txt, they will be saved under the names MyFile(2).txt, MyFile(3).txt, etc.
 

Moving, Copying and Deleting Files

The UploadedFile object provides methods that enable you to move, copy or delete uploaded files. These methods are

file.Move( NewName As String )
file.Copy( NewLocation As String, Optional Overwrite)
file.Delete

Depending on the NewName argument, the Move method will either move the file to another directory or rename it. Suppose the file abc.txt has been uploaded to the directory c:\Upload. Then the call

file.Move "c:\WINNT\abc.txt" will move the file to the directory c:\WINNT, whereas the call
file.Move "c:\Upload\xyz.txt" will simply rename the file.

It's important to know that the Move method has a side effect: once this method is successfully called, the Path property of this file object will point to the new location/name.

The Copy method copies the file to a new location/name. NewLocation must be a fully qualified path. The Overwrite parameter, if set to True or omitted, instructs the Copy method to overwrite an existing file at the new location. If set to False, it will cause the method to fail should a file at the new location already exist. Unlike Move, this method does not affect the Path property.

You may choose to use the Delete method if, for example, you are saving the file in the database as a blob and no longer need it in your upload directory. Saving files in the database is our next topic.
 

Saving Files in the Database as Blobs

Many database management systems like MS Access or SQL Server will let you store arbitrary files as "binary large objects" (BLOBs). An MS Access table can store binary files in data fields of the type OLE Object. In SQL Server, the corresponding data type is called IMAGE. The stored files can later be retrieved for downloading or displaying using ADO.

AspUpload allows you to save uploaded files in the database in as little as 1 line of code! Let's look at our third set of sample files. The file Test3.htm is almost identical to Test1.htm, so we won't show it here. The file UploadScript4.asp does deserve our attention:
 
 

<HTML> 
<BODY> 

<% 
Set Upload = Server.CreateObject("Persits.Upload.1") 
Upload.Save "c:\upload" 
On Error Resume Next 
For Each File in Upload.Files 

File.ToDatabase "DSN=data;UID=sa;PWD=xxx;", "insert into Blobs(id, Path, BigBlob) values(12, '" & File.Path & "', ?)"
if Err <> 0 Then 
Response.Write "Error saving the file: " & Err.Description
Else 
File.Delete 
Response.Write "Success!"
End If

Next
%> 
</BODY> 
</HTML>

The line

On Error Resume Next

instructs ASP not to display error messages when exceptions occur, but to store the exception codes and description in the built-in Err object instead and continue the execution of the script.

The next line

File.ToDatabase "DSN=data;UID=sa;PWD=xxx;", "insert into Blobs(id, Path, BigBlob) values(12, '" & File.Path & "', ?)"

is all it takes to save a file in the database. Let's examine the two arguments of this method:

The first argument is an ODBC connection string in the following format:

"DSN=datasource;UID=userid;PWD=password;<other optional parameters>"

The second argument is an SQL INSERT or UPDATE statement with one and only one question mark sign (?) which serves as a place holder for the file being saved. In this example, our underlying database table Blobs consists of three columns: an integer ID, a VARCHAR Path, and an IMAGE BigBlob. This SQL INSERT statement puts a 12 into the ID column, file path into the Path column and the actual file into the BigBlob column.

The next line checks if the statement right before it executed successfully. If it did the Err object is 0 and the file will be deleted (line File.Delete) since it is now saved in a database table and no longer needed in the upload directory. Otherwise, Err contains a numeric error code, and Err.Description contains the verbal description of the exception.

It is not uncommon to store GIF and JPEG images in a database table. To retrieve an image from the table and display it on an HTML page, you don't need to use any third-party component. ADO will do the job for you.

Put a regular <IMG> tag on your HTML page with the SRC attribute pointing to an ASP script, e.g.

<IMG SRC="GetImage.asp?id=4">

The GetImage.asp script may look like this:

<%
Set db = Server.CreateObject("ADODB.Connection")
db.Open "data"
Set rs =db.Execute("SELECT BigBlob FROM Blobs where id = " & Request("id") )
Response.ContentType = "image/jpeg" '(or "image/gif")
Response.BinaryWrite rs("BigBlob")
%>


Where To Get More Info on AspUpload

For the complete AspUpload documentation, and to download your free evaluation copy, please visit the Persits Software web site at http://www.persits.com/aspupload.html. The registration fee for this component is $99.00 (single CPU license).

Frequently Asked Questions

Q:  Will AspUpload work with any version of ASP?
A:  No. Early versions of the ASP's Request object did not provide the BinaryRead or TotalBytes methods which the component heavily relies on. The best way to test whether your version of ASP allow uploading is to execute simple script like <% n = Request.TotalBytes %> and see if the method is recognized by your ASP module.

Q:  Where can I get the latest version of ASP?
A: It depends on the type and version of your web server. If you are using PWS or IIS 3.0 you can download the latest version of ASP from http://www.microsoft.com/office/intranet/modules/asp411s3.asp.
If you are using IIS 4.0 you may need to install Option Pack 4 downloadable from http://www.microsoft.com/iis.

Q:  Does Microsoft Internet Explorer 3.0 support file uploading?
A:  By default, no. But there is an IE3 upload add-on available from http://www.microsoft.com/msdownload/iebuild/ie3add_win32/en/ie3add_win32.htm.
 

About the Author

Peter Persits is the founder and president of Persits Software, Inc., the maker of the popular ASP components AspNTUser, AspGrid, AspAccessControl, AspUpload and AspEmail. Peter has been developing software for over 10 years. He holds a Master's degree in Computer Science from American University (Washington, DC) and is a Microsoft Certified Solution Developer. He currently lives in Arlington, VA.


About the Author

From ASP101

Articles originally posted on ASP101.com

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date