Your browser must be RFC 1867-compliant to be able to upload files. Netscape 3.0+ and Microsoft IE 4.0+ are RFC 1867-compliant. IE 3.0 requires a special file upload add-on (patch) available at download.com (search for "upload patch").
System Requirements
- Full ADO support. You can now save files into the database and export files out of the database using ADO objects rather than ODBC which is much more intuitive and easy to code. You can even pass an uploaded file as a parameter to a transactional SQL stored procedure.
- MacBinary support. AspUpload automatically detects if a file was uploaded from a Macintosh, and if so, extracts the "data fork" from it so it can be read on a PC.
- Image size extraction. AspUpload can determine the size of GIF, JPEG and BMP images.
- Uploading to memory. If the ultimate destination of uploaded files is a database, consider using uploads to memory rather than hard drive for better performance and security.
- Uploading entire directories. This feature is available when the XUpload 2.0 ActiveX control is used on the client side. AspUpload provides an enhanced version of the CreateDirectory method which can create multi-level paths and optionally ignore the "directory already exists" error. Sample scripts can be found in the XUpload 2.0 installation.
- New properties and methods that you have been asking for, such as File.ContentType, File.SaveAs, Upload.IgnoreNoPost, Upload.OpenFile, and more.
- A setup program and 15 new code samples.
Windows 2000 and IIS 5.0, orAbout Code Samples
Windows NT 4.0 and IIS 3.0/IIS 4.0, or
Windows 95/98 and Personal Web Server with ASP support.
All the code samples mentioned in this manual, and many others not mentioned, can be found in the \Samples sub-directory of the AspUpload installation. A complete index of code samples can be found in the file \Samples\SAMPLE_INDEX.HTM. The AspUpload Setup program created the virtual folder /AspUpload on top of the \Samples directory so that you can run the sample files with your browser using URLs of the type http://localhost/AspUpload/Test1.asp.Getting StartedAll database-related code samples were tested against a SQL Server database that can be re-created on your system by running the SQL script \Database\CreateTables.sql. All non-transactional samples will also work against a MS Access database located in the file \Database\ImageDB.mdb.
A complete description of the AspUpload object properties and methods can be found in the file ObjectReference.htm.
This is out first HTML file Test1.asp:
<HTML>
<BODY
BGCOLOR="#FFFFFF">
Notice the ENCTYPE="multipart/form-data" attribute in the FORM tag. It instructs the browser to send the entire file to the server and not just the file name entered in the input text box. It is absolutely mandatory that your uploading forms contain this attribute, or no uploading can be performed.
Let us now look at the corresponding uploading script UploadScript1.asp:
<HTML>
<BODY> <%
Count = Upload.Save("c:\upload") <% = Count %> files uploaded. </BODY>
|
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 them in the specified local directory. 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.
We can now go ahead and try to upload a few files. 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.
<HTML>
<BODY
BGCOLOR="#FFFFFF">
File
2:<INPUT TYPE=FILE NAME="FILE2">
Description
2:<INPUT TYPE=TEXT NAME="DESCR2"><BR>
<INPUT
TYPE=SUBMIT VALUE="Upload!">
<HTML>
<BODY> <%
Upload.Save "c:\upload" Files:<BR>
<P> Otheritems:<BR> <%
</BODY>
|
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 Request.Form collection. That's where the Upload.Form collection comes to the rescue. This collection is almost identical to Request.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>. We have chosen to have 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.
<%
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 larger than the maximum should be truncated (if set to False or omitted), or rejected with an error exception (if set to True).
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.
<HTML>
<BODY BGCOLOR="#FFFFFF">
<!--#include file="AspUpload.inc"-->
<HTML>
<%
Upload.Save "c:\upload"
File.AllowAccess "Domain1\ppersits", GENERIC_ALL File.DenyAccess "jsmith", GENERIC_ALL Success! </BODY> </HTML> |
File Test3.asp is virtually identical to Test1.asp. File UploadScrip3.asp begins with the line
<!--#include file="AspUpload.inc"-->
It instructs ASP to include the file AspUpload.inc into the page. This file is shipped with the component and contains several Windows NT constant definitions that you will need to manipulate file attributes and ACLs.
The line
File.Attributes = FILE_ATTRIBUTE_READONLY + FILE_ATTRIBUTE_HIDDEN
will set the file attributes to Hidden and Read-only. The property Attributes is read-write, so it is perfectly legal to say
File.Attributes = File.Attributes + FILE_ATTRIBUTE_READONLY
if you want to add a new attribute while leaving existing attributes intact.
The lines
File.AllowAccess "Domain1\ppersits",
GENERIC_ALL
File.DenyAccess "jsmith",
GENERIC_ALL
add an allowance access control entry (ACE) and a denial ACE to the file's Access Control List (ACE). You can also use the RevokeAllowance and RevokeDenial to remove allowance and denial ACEs from the file's ACL. To set the file's owner use the SetOwner method.
The attribute and ACL manipulation methods are subject to Windows NT security restrictions. You may need to use the LogonUser method to impersonate an administrative NT account before using these methods. See Object Reference for more information.
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.
The usage of the methods File.Copy and File.Delete to rename uploaded files is demonstrated in the code sample UploadScript10.asp. An alternative approach to file renaming using the method File.SaveAs (new in AspUpload 2.0) is demonstrated in UploadScript11.asp.
<HTML>
<BODY> <% Set Upload = Server.CreateObject("Persits.Upload.1")
For Each File in Upload.Files
Response.Write "Success!" </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=MyImages;UID=sa;PWD=xxx;", _
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 MyImages consists of two columns: a VARCHAR Filename, and an IMAGE Image1. This SQL INSERT statement puts the 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 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.
To save an arbitrary file from your hard drive to a database, use the UploadManager.ToDatabaseEx method (new in ver. 1.4) , which accepts a file path as the first parameter. The other two parameters are the same as that of the File.ToDatabase method:
Upload.ToDatabaseEx "c:\myfile.txt", "DSN=data;UID=sa;PWD=;", "insert into..."
Using ADO Objects (New in AspUpload 2.0)
ConnectStr = "Driver={SQL
Server};Server=MYSERVER;Database=Pubs;UID=sa;PWD="
Set rs = Server.CreateObject("adodb.recordset")
rs.Open "MYIMAGES",
ConnectStr, 2, 3
rs.AddNew
Set File = Upload.Files("FILE1")
If Not File Is Nothing
Then rs("Image1").Value = File.Binary
' set other fields if
necessary
rs.Update
%>
Exporting Files from the Database
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")
' let the browser know
the file name
Response.AddHeader
"Content-Disposition", "filename=yourfile.ext"
' let the browser know
the file size
Response.AddHeader
"Content-Length", "545645"
Response.BinaryWrite
rs("BigBlob")
%>
To export a BLOB from the database to your hard drive, you can use the method Upload.FromDatabase which allows you to perform the exporting in 1 line of code. See Object Reference (section UploadManager Methods) for the full description of this method.
AspUpload 2.0 also offers an ADO-based method for exporting files from the database using the method Upload.FromRecordset. The usage of that method is demonstrated in the code sample ExportFilesFromDB.asp.
If the ultimate destination of uploaded files is a database, you may consider using uploads to memory rather than hard drive for better performance and security. To use this feature, you must call Upload.SaveToMemory instead of Upload.Save <path>. The differene betoween the two methods is that the former does not save files to the hard drive. It does, however, create both Files and Form collections in memory. An uploaded file can be accessed via the File.Binary property if you wish to save it to the database using ADO, or File.SaveAs method if you want to save it on hard drive under a certain name. Here is an example:Image Size and Type Extraction (new in AspUpload 2.0)<%
Set Upload = Server.CreateObject("Persits.Upload.1")
' ensure a unique name when calling File.SaveAs
Upload.OverwriteFiles = False
Count = Upload.SaveToMemoryIf Count = 1 Then ' 1 file uploaded
Set File = Upload.Files(1)' retrieve destination file name from a HIDDEN form item
Path = "c:\upload\" & Upload.Form("Filename")
' Side effect: SaveAs sets changes File.Path property to a new value.
File.SaveAs Path
Response.Write "File was saved as " & File.Path
Else
Response.Write "No files were uploaded."
End If
%>Uploading to memory is demonstrated in the code samples UploadScript8.asp and UploadScript11.asp.
AspUpload 2.0 is capable of obtaining image size information from GIF, JPEG and BMP files via the properties UploadedFile.ImageWidth and UploadedFile.ImageHeight. You can use these properties to limit the size of uploaded images. To determine the type of an uploaded image, you may use the property UploadedFile.ImageType which returns the strings "GIF", "JPG" or "BMP" for GIF, JPEG and BMP files, respectively. If an uploaded file is not an image or its type cannot be determined, this property returns the string "UNKNOWN". The following example demonstrates the usage of these properties (another example can be found in the sample file UploadScript7.asp):User Account Impersonation<%
Set Upload = Server.CreateObject("Persits.Upload.1")
Upload.Save "c:\upload"
For Each File in Upload.FilesIf File.ImageType <> "GIF" and File.ImageType <> "JPG" ThenNext
Response.Write "GIF or JPG files only please!"
Exit For
End IfIf File.ImageWidth > 150 Then
Response.Write "Image width cannot exceed 150 pixels."
Exit For
End IfIf File.ImageHeight > 200 Then
Response.Write "Image height cannot exceed 200 pixels."
Exit For
End If
%>
By default, ASP scripts run under the security context of the "Anonymous" user account IUSR_machinename. This user account usually has very few permissions and if your script is uploading files to a remote machine you are likely to receive the error "Access is denied." To overcome this problem, you can use the LogonUser method which impersonates an arbitrary user account with sufficient permissions. This method accepts three parameters: a domain name, username and password. Once a successful call to the LogonUser method is made, the rest of the script on that ASP page will run under the security context of the specified user account. For example,Preserving "Last Modified" Date/Time Information of Uploaded Files<%
Set Upload = Server.CreateObject("Persits.Upload.1")
Upload.LogonUser "mydomain", "Administrator", "xxxxxxxxx"
' Upload to a remote drive
Count = Upload.Save("\\someserver\cdrive\upload")
%>If an empty string is specified for the domain name, the local machine will be used to validate the username and password. If your virtual directory has the "Run in separate memory space" option checked, the current user (IUSR_xxx) must have the "Act as part of the operating system" privilege or you will get the error "Required Privilege not held by the client." The usage of the LogonUser method is demonstrated in the code sample UploadScript12.asp.
Currently, browsers do not send the "Last Modified" information along with the files being uploaded as it is not part of the RFC-1867 specification, so if you use form-based uploading the file dates cannot be preserved. However, if you use the Persits Software client upload tools XUpload ActiveX control or JUpload Java applet (the latter is currently under development) the files' dates can be preserved as these tools do send the files' "Last Modified" information to the server. A custom MIME header, X-File-Date, is used as follows: X-File-Date: Wkd Mon DD HH:MM:SS YYYY. The time is converted to Greenwich Meridian Time (GMT) to account for possible time difference between the client and server machines. For example:Encryption SupportX-File-Date: Sun May 01 20:27:01 1994
To capture and use this information with AspUpload, simply set the PreserveFileTime property to True before calling Upload.Save, as follows:
Upload.PreserveFileTime = True
Starting with build 1.4.0.2, AspUpload is capable of encrypting uploaded files, thus making your Web-based file management system truly secure. This functionality requires AspEncrypt, a cryptographic component from Persits Software, Inc. To learn how to make file uploading and downloading encryption-enabled, and to download your free trial copy of AspEncrypt, visit the AspEncrypt.com web site at www.aspencrypt.com/task_upload.html.Complimentary Features: Directory Listing, Downloading, and ActiveX Registration
The Directory collection consists of DirectoryItem objects. Each DirectoryItem object represents a file or subdirectory inside this directory. All the file and subdirectory items are always grouped together, with subdirectories preceding files in the collection. Within the subdirectory and file groups, items can be sorted by name, type, size, creation time, last modification time and last access time. Items are always sorted in an ascending order.
The following code snippet creates and scrolls through a Directory collection which represents all files in the folder "c:\mydir" sorted by file type.
<%
Set
Upload = Server.CreateObject("Persits.Upload.1")
Set
Dir = Upload.Directory( "c:\mydir\*.*", SORTBY_TYPE)
For
Each item in Dir
Response.Write item.FileName &"<BR>"
Next
%>
The first argument of the Directory property is a directory name and a file name which can contain wildcard characters (* and ?). The second argument is optional and, if used, must be set to one of the Sort-by values defined in AspUpload.inc. The default value is SORTBY_NAME (numeric 1).
As we just mentioned, the items in the collection are always sorted in an ascending order. If you need to list files in a descending order instead, you will have to scroll through the collection backwards using integer indexes rather than a For-Each statement, e.g.
<%
Set
Upload = Server.CreateObject("Persits.Upload.1")
Set
Dir = Upload.Directory( "c:\mydir\*.*", SORTBY_TYPE)
For
i = Dir.Count To 1 Step -1
Response.Write Dir(i).FileName &"<BR>"
Next
%>
<%
Set Upload = Server.CreateObject("Persits.Upload.1")
Upload.SendBinary
"c:\dir\myfile.ext", True
%>
This method internally uses Response.BinaryWrite. If the second parameter is set to True or omitted the method will set Response.ContentType to an appropriate value based on the file's extension and registry settings. If the extension is unknown or missing, Response.ContentType will be set to "application/octet-stream". If the second parameter is set to False, Response.ContentType will not be set by the method so that you can set it to any value you need.
We illustrate the use of both features in the sample files DirectoryListing.asp and Download.asp.
<%
Set Upload = Server.CreateObject("Persits.Upload.1")
Upload.Save "c:\Upload"
For Each File in
Upload.Files
If the optional second parameter is set to False, the method will unregister the library:
Upload.RegisterServer File.Path, False
The registry values used to disable the "dangerous" features are located under the key
HKEY_LOCAL_MACHINE\SOFTWARE\Persits Software\AspUpload.
By default, all the registry values are set to 0 (enabled). Setting them to 1 (or any non-zero value) would disable the corresponding feature.
The following methods can be disabled as follows:
For pricing and ordering information, latest news and a live demo, please visit the AspUpload web site at http://www.aspupload.com. For technical support please write to support@aspupload.com. For general and sales inquiries write to info@aspupload.com.