![]() |
![]() |
||||||||||
|
AspUpload
2.0 Introduction AspUpload 2.0 is an Active Server component which enables an ASP application to accept, save and manipulate files uploaded with a browser. The files are uploaded via an HTML POST form using the <INPUT TYPE=FILE> tag. The AspUpload component is invoked by an ASP script located on a Windows NT/2000 server running Internet Information Server (IIS), or Windows 95/98 machine running Personal Web Server (PWS), and Active Server Pages (ASP) version 1.0b or higher . The component parses the posting received from the browser and saves the received files on the server's hard drive. AspUpload can then manipulate the uploaded files in a number of ways which include ACL manipulation, attribute changes, saving to a database, etc. 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"). What's New in Version 2.0
Getting Started Let's create a simple HTML form which will let us upload up to three files, and a script to handle the uploading. This is out first HTML file Test1.asp: <HTML> <FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="UploadScript1.asp"> <INPUT TYPE=FILE SIZE=60 NAME="FILE1"><BR> </FORM> </BODY> 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:
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. Working with FILES and FORM Collections Let's take a look at our second set of files, Test2.asp and UploadScript2.asp. <HTML> <FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="UploadScript2.asp"> File
1:<INPUT TYPE=FILE NAME="FILE1"> File 2:<INPUT TYPE=FILE NAME="FILE2"> </FORM> </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: Other items: 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! NOTE: The handling of multi-select HTML items such as <SELECT MULTIPLE> is slightly more complicated. For a code sample, see the files Test13.asp and UploadScript13.asp. Setting a Limit on File Size Suppose you need to limit the size of the files being uploaded to prevent irresponsible users from congesting your server's disk space. All you need to do is call the SetMaxSize method on your Upload object just before calling Save: <% 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). 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. Manipulating File Attributes and Access Control Lists AspUpload enables you to modify the attributes and Access Control Lists (ACLs) of the files once they have been downloaded. This will be illustrated by the next set of sample files, Test3.asp and UploadScript3.asp. <HTML> <FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="UploadScript3.asp"> <INPUT TYPE=FILE SIZE=60 NAME="FILE1"><BR> <INPUT TYPE=SUBMIT VALUE="Upload!"> </BODY>
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 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. Moving, Copying, Renaming and Deleting Files The UploadedFile object provides methods that enables you to
move, copy or delete uploaded files. These methods are file.Move( NewName As String )
file.Move "c:\WINNT\abc.txt" will
move the file to the directory c:\WINNT, whereas the call 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. Saving Files to a Database AspUpload will allow you to save uploaded files in the database
in as little as 1 line of code! Let's look at our next set of sample
files. The Test4.asp is once again almost identical to Test1.asp
and Test3.asp, so we won't show it here. The file UploadScript4.asp
does deserve our attention:
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;", _ "insert into MyImages(filename, Image1) values('" & File.Path & "', ?)"
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)
AspUpload 2.0 has full ADO support which allows you to save files in the database using the traditional ADO objects rather than ODBC. The UploadedFile object provides a new property, Binary, which renders the underlying file data in the Safe-array-of-bytes format compatible with ADO recordset fields. The following code sample (also found in the file UploadScript6.asp) demonstrates how to use the File.Binary property to save a file in the database using an ADODB.Recordset object:
<% ConnectStr = "Driver={SQL Server};Server=MYSERVER;Database=Pubs;UID=sa;PWD=" Set File = Upload.Files("FILE1") ' set other fields if necessary
Notice that the Binary property enables us to assign a file to a recordset field much the same way as any numeric or text value. A similar approach can be taken in order to pass a file as a parameter to a transactional SQL stored procedure as demonstrated by the code sample StoredProcedure.asp. The SP itself can be found in the sub-directory \Database\MyStoredProc.sql. 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: <% 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. Uploading To Memory (new in AspUpload 2.0)
Image Size and Type Extraction (new in AspUpload 2.0)
User Account Impersonation
Preserving "Last Modified" Date/Time Information of Uploaded Files
Encryption Support
Complimentary Features: Directory Listing, Downloading, and ActiveX Registration AspUpload provides three additional features that are not directly
connected to the product's uploading functionality. These features are
Directory Listing, File Downloading and ActiveX Registration.. Directory ListingBesides Form and Files collections, UploadManager provides one more collection, Directory, which represents a file directory on your hard drive. Unlike the other two collections, Directory does not require that the Save method be called to be populated. 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. <% 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. <% The snippet will display all files followed by all directories,
and both files and directories will be sorted by file type in a descending
order. File DownloadingIt may sometimes be necessary to let users download file which do not reside in an IIS virtual directory. You can use the AspUpload component to read an arbitrary binary file from your hard drive and send it to the client browser via the UploadManager's SendBinary method: <% 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. ActiveX RegistrationUploadManager provides a method, RegisterServer, that mimics the behavior of the REGSVR32 utility. You can use it to provide the automatic registration of ActiveX DLLs being uploaded: <% Upload.RegisterServer File.Path Next If the optional second parameter is set to False, the method will unregister the library: Upload.RegisterServer File.Path, False Disabling Advanced Features in a Web-Hosting Environment
|
|||||||||||