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>