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 http://www.microsoft.com/msdownload/iebuild/ie3add_win32/en/ie3add_win32.htm.
REGSVR32 c:\AspUploadDir\AspUpload.dll.
from the MS DOS or Start/Run prompt. To be able
to run the sample scripts you will need to add the directory c:\AspUploadDir
to the list of IIS virtual directories with the Execute permission enabled
using Microsoft Management Console.
This is out first HTML file Test1.htm:
<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 then 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> Other items:<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 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>. 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 bigger 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.htm is virtually identical to Test1.htm. 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.
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.
<HTML>
<BODY> <%
Upload.Save "c:\upload" On Error Resume Next
Response.Write "Success!" </BODY>
|
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 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.
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")
Response.BinaryWrite
rs("BigBlob")
%>
To export a BLOB from the database to your hard drive, you can use the method Upload.FromDatabase (new in ver. 1.3) 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.
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
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: