Welcome to SoftArtisans FileUp

Welcome to FileUp Version v5.3.1!

Last update: 05/2010
This is the documentation for FileUp Standard Edition (FileUpSE) and FileUp Professional Edition (FileUpPE). Documentation for XFile, which is included with FileUpPE, can be found at the SoftArtisans Support Site. For information on all FileUp editions, please see FileUp Editions.
Understanding the Documentation Structure
  • Introduction
    Describes the basic features and requirements of FileUp.

  • Installation
    Includes instructions for automatic and manual installation as well as registry settings.

  • Making FileUp Available to .NET Applications
    Describes special steps which are needed for including FileUp in a .NET application, including configuring your application to use the HttpModule.

  • Configuration and Application Planning
    Provides recommendations to ease development, facilitate application troubleshooting and configure the application for the production environment.

  • Getting Started
    Provides a first walk-through of the simplest upload and download in both ASP and ASP.NET.

  • Programmer's Guide
    Includes tutorials that will show you how to use FileUp in the context of real-world scenarios.

  • Transactional Processing
    Provides instruction for understanding and creating a transactional upload application.

  • Common Client-Side Solutions
    Demonstrates how adding the client-side tool XFile, can enhance your file-transfer application.

  • Programmer's Reference
    Describes each object, method, and property of FileUp, and the three bonus tools - Archive, FileManager, and SMTPMail.

  • Programmer's Samples
    Includes an index of the many samples you received with FileUp, and instructions on setting up the samples and associated database.

Copyright © 2010 SoftArtisans, Inc. All rights reserved.


What is SoftArtisans FileUp?

SoftArtisans FileUp is a server-side file transfer tool. FileUp processes uploads sent from a client over HTTP to a server running Microsoft Internet Information Server (IIS). Uploads are typically submitted from a web page or from a client-side ActiveX control such as SoftArtisans XFile. Uploaded files can be saved on the web server or to another machine on the same local network as the web server.

FileUp can process any type of uploaded file. Developers can use FileUp to receive and process user input, while staying within the context of their ASP or ASP.NET application.

FileUp can also be used to simply and securely download files from the web server to the user's browser.

Additional components are bundled with FileUp to provide file management, compression and SMTP functionality. Manipulate files, change ACLs and permissions, register DLLs, create and extract zip and cab files, and send emails all in a single, easy-to-use package.

All of the above is included in FileUp Standard Edition. To add a client-side solution that includes XFile, consider FileUp Professional Edition or FileUp Enterprise Edition. To compare the feature set of the three editions, please continue on to the Editions Comparisons page.


What is SoftArtisans XFile?

XFile can be purchased separately or is included as part of the FileUp Professional Edition package.

SoftArtisans XFile is a powerful ActiveX object with a non-visual COM file transfer engine. XFile is a complete HTTP client that may be used from Internet Explorer for Windows, Visual Basic, or through the Windows Shell Extension.

XFile contains additional features that help extend the feature-set of FileUp. XFile is included in FileUp Professional Edition and Enterprise Edition, or it can be purchased separately.

XFile's file transfer engine submits uploads from client to server, receives downloads, and transfers files from server to server. The file transfer engine (the XFRequest object) can be used in client-side HTML code through the <object> tag.

In addition to the file transfer engine - XFile's principal object - XFile includes a visual upload control and a visual download control. Note that the file transfer engine (the XFRequest object) always sends and receives the file transfer, while the visual controls provide a graphical user interface to use with the file transfer engine. You must use the file transfer engine, but you do not have to use the visual controls.

There are two editions of XFile:

  • XFileSE
    XFile Standard Edition (XFileSE) can be used with either FileUpSE or FileUpEE on the server. XFileSE can handle uploads of up to 4 GB. XFileSE does not support resumable uploading or downloading.
  • XFileEE
    XFile Enterprise Edition (XFileEE) can be used with either FileUpSE or FileUpEE on the server. There is no upload size limit when you use XFileEE with FileUpEE on the server. XFileEE includes resumable uploading and downloading.

For more information on edition differences, see FileUp Editions Comparison.


FileUp Editions Comparison

FileUp Editions

  • FileUp Standard Edition (FileUpSE)
    FileUpSE enables your web application running in IIS to securely and quickly accept and process uploaded files. FileUpSE can accept upload requests up to 4-GB in size with minimal server resources. (Note: Most browsers can only send up to 2-GB. You will need to use FileUpPE, which includes XFile to surpass this 2-GB limitation.) FileUp can accept a form-based RFC-1867 compliant request from a client as simple as the browser, or from an intelligent client such as XFile.

  • XFile Standard Edition (XFileSE)
    XFileSE is an intelligent client that can be used to generate file upload and download requests. XFile is an ActiveX control that can be used in Internet Explorer or any COM supporting environment such as Visual Basic. XFile provides programmatic control over the client-side user experiences as well as control over the content of the request. For file uploads, XFile must be used with a server side tool that is capable of processing an RFC-1867 compliant POST, such as FileUp.

  • FileUp Professional Edition (FileUpPE)
    FileUpPE combines server-side processing power of FileUpSE with the client-side ActiveX control, XFileSE. By using both in combination, you gain control over both the server and client sides of the transfer process.

  • FileUp Enterprise Edition (FileUpEE)
    FileUpEE tackles the multi-faceted needs of any secure file transfer application. FileUpEE easily handles multi-gigabyte file transfers, supports Web farms and functions across firewalls. With no limits on the number or size of files you can upload, FileUpEE solves the server-crippling upload limitations of IIS and ASP.NET. FileUpEE inclues the Enterprise Edition of XFile.

Feature | FileUp Enterprise | FileUp Professional | FileUp Standard
Secure Web-to-file server transfers | Yes |  |
Send/process SOAP requests | Yes |  |
Allows centralized or replicated secure file storage | Yes |  |
Centrally locate transfer logic | Yes |  |
Audit transfers easily | Yes |  |
Data administration | Yes |  |
File selection GUI | Yes | Yes |
Preset file(s) to/from client | Yes | Yes |
Rich client-side ActiveX control | Yes | Yes |
Multi-file progress indicator | Yes | Yes |
Request size maximum | Unlimited | 4 Gigabytes | 4 Gigabytes
Bypass ASP.NET, IIS limits | Yes | Yes | Yes
Easy to use | Yes | Yes | Yes
Process all file types | Yes | Yes | Yes
Data integrity | Yes | Yes | Yes
Secure client-to-Web server transfers | Yes | Yes | Yes
Versatile file manipulation | Yes | Yes | Yes
Secure Web-to-file server transfers

Enterprise Edition: Transfer files via HTTP(S) from public Web servers through any number of firewalls to a file server, where sensitive information can remain secure.

Send/Process SOAP requests

Enterprise Edition: Uploads from Web server to file server are submitted as SOAP requests, allowing your firewall to reject all non-SOAP requests. The SOAP request sends all user-submitted form data to the file server with the upload. Choose to have FileUpEE automatically create the SOAP request, or create the request yourself via ASP or ASP.NET.

Allows centralized or replicated secure file storage

Enterprise Edition: Within multi-Web server architectures uploaded files are stored in a central, shared file location. A file that is uploaded to a server in a Web farm is immediately available to be downloaded from any other server in that Web farm. There is no need to replicate data between all of the Web servers.

Centrally locate transfer logic

Enterprise Edition: Application logic specific to the transfer - such as a database connection string - can be optionally contained on a secure centrally located file server. When the application requires modification, the information only needs to be changed on the file server - not on each server in the Web farm.

Audit transfers easily

Enterprise Edition: Create an audit database that details information about the upload/download. Track when files are sent, time of completion, size of files, etc.

Data administration

Enterprise Edition: All files are transferred with fully extensible properties to describe them. And with file size concerns no longer an issue, IT Departments can use FileUpEE to back up large files or even entire servers to a disaster recovery system.

File-selection GUI

Enterprise and Professional Editions: Clean, customizable interface for a) multiple file and directory uploads, b) File/Folder list sorting by name, date, or size, c) color parameters for background, buttons, file list box, and text, d) multiple file extension filters and e) directory navigation buttons.

Preset file(s) to/from client

Enterprise and Professional Editions: Preset the client file path for a download or the file to upload from a user's hard disk.

Rich client-side ActiveX control

Enterprise and Professional Editions: Support SSL, proxies, and multiple authentication mechanisms, make multiple HTTP Gets or Posts in a single operation, generate events for capture by Internet Explorer or Visual Basic.

Multi-file progress indicator

Enterprise and Professional Editions: Display an accurate progress indicator for both an individual file and the total transfer while uploading and downloading.

File size maximum

Professional and Standard Editions: Transmit file upload request of up to 4 gigabytes. Enterprise Edition: There are no limitations on the number or size of files you can upload. Back up entire hard drives in a single step.

Bypass ASP.NET, IIS limits

All Editions: Solve potentially server-crippling upload limitations in ASP.NET and IIS. By intercepting transfer requests with the HttpModule, FileUp buffers a small portion of the upload into physical memory, then caches it to disk, before gracefully passing it to IIS on the Web server.

Easy to use

All Editions: Intuitive object models, clear documentation, and extensive working samples make all editions of FileUp - and the bonus tools they include - very easy to use.

Process all file types

All Editions: There are no file type limitations in any of the editions. Transfer .doc, .pdf, .psd and .mpeg files just to name a few.

Data Integrity

All Editions: Verify the integrity of uploaded data when transferring files from a browser to a Web server. Enterprise Edition: Verify data integrity when uploading from browser to Web server or from Web server to file server.

Secure client-to-Web server transfers

All Editions: Uploads from the client to the Web server can be SSL encoded so that the information is encrypted during transmission. In contrast, there is no means for doing that using standard FTP.

Versatile file manipulation

All Editions: Compress uploads and decompress downloads in zip format. Filter files by type, size, and name.


What Edition is Best for my Application?

Requirement | Appropriate Edition
I need to automate uploads. I want files pre-loaded for the user, or I want uploads to happen with minimal user interaction. | The browser alone cannot provide this functionality. You must use an intelligent client, such as XFile. Use FileUp Enterprise Edition, FileUp Professional Edition, or purchase XFile Standard Edition alone to use with your own server-side processing tool.
My users need to be able to upload an unknown number of files. | An HTML form requires one file input element for each file to be uploaded. XFile allows the user to select any number of files. With XFile's file selector, the user can select multiple files by holding down the shift key and add all of the files at once to XFile's file collection. Additionally XFile can be scripted to add entire directories. Use FileUp Enterprise Edition or FileUp Professional Edition.
I need to upload more than 2GB in one upload request. | Whether this is the result of many small files or one large file, WinInet, the transfer engine used by Internet Explorer, does not support Request sizes greater than 2GB. To bypass this limitation, you will need to use XFile. Use FileUp Enterprise Edition (no size limit) or FileUp Professional Edition (4GB limit).
I need to upload more than 4GB in one upload request. | Whether this is the result of many small files or one large file, XFileSE does not support Request sizes greater than 4 GB. Additionally, IIS will not accept requests with a content-length header that indicates that request is greater than 4GB. To bypass both of these limitations, you will need to use FileUp Enterprise Edition.
I do not want to save the files on my webserver, I plan to save them on a file server. | FileUp Standard & Professional Editions can be used as long as the file server is exposed as a network share; however, this reduces the security of your file server to the same level as that of your web server. If you are storing the files on a file server for security's sake, you should place the file server behind a firewall and should not expose any directories on the file server to the webserver. Use FileUp Enterprise Edition to get the file to your file server.
I need to download more than one file at a time. | FileUp Standard Edition's Transfer File method can be used to download a file that is not stored in a virtual directory; however it can only transfer one file at a time. FUSE is packaged with an accessory component that can package multiple files in either a zip or cab file. Alternately, XFile can be used to make multiple requests in what appears to be one transaction to the end user. Use FileUp Professional Edition or FileUp Enterprise Edition to do so.
I want to put limitations on the kinds of files that are uploaded. | You can use FileUp Standard Edition to filter files that are saved to the server, but because this is done server side, you will not be preventing the files from arriving on the server with the request. Your option is to save or not to save based on your own criteria (file size, file extension, etc). By using XFile in FileUp Professional or Enterprise Editions, you can place limitations on the files before they leave the client. In other words, you are preventing the files from being sent at all.
I need to support resumable uploading and downloading. | Only FileUpEE supports resumability.
I need to upload files to a database. I need to download files from a database. | All editions of FileUp support uploading and downloading from a database.
I need to zip files before I upload them. I need to unzip files that have been downloaded. I need to unzip files server-side. | FileUp Standard Edition distributes with SoftArtisans Archive, which can unzip files on the server. XFile also distributes with Archive, to allow client-side zipping and unzipping of archived files.


Features and Benefits

FileUp Standard Edition

  • Accepts upload requests up to 4 GB* in ASP.NET and up to 2 GB in ASP with or without in-memory caching of the requests.

  • Server-side control - does not require installation on the user's computer.

  • Supports database uploads and downloads in ASP and ASP.NET.

  • Supports transactional uploading :

    • Guaranteed synchronization between upload processing and database transactions.
    • Full participation with COM+ transactions.
    • Vastly simplified error handling and guaranteed integrity when uploading multiple files.

  • Includes a server-side progress indicator that lets users monitor the progress of their uploads.

  • Includes Performance Monitor Counters that allow you to precisely monitor upload and download performance.

  • MD5 allows you to verify the integrity of uploaded data.

  • Recursive Directory Uploads - when used in conjunction with our client-side tool XFile, entire directory trees can be uploaded in a single operation.

  • Unicode file name/form value support - works even better with SoftArtisans XFile!

  • Can upload to memory rather than to disk for better performance and security, or to disk for better memory management.

  • Resumable downloads - When used in conjunction with a resumable download client tool such as GetRight®, FileUp supports resumable downloads that are secure.

  • For Macintosh clients, MacBinary is supported. Files uploaded from a Macintosh can be saved in MacBinary format or with extracted data fork.

  • Includes three bonus components:

    • SoftArtisans Archive - a programmer's tool for the creation and extraction of ZIP and CAB archives.
    • SoftArtisans FileManager - an easy-to-use solution that meets all your file management needs.
    • SoftArtisans SMTPMail - a full-featured SMTP email client.

XFile Standard Edition

(Purchasable separately or included in FileUp Professional Edition)
  • Non-visual file transfer engine
    • Allows multiple HTTP Gets or Posts in a single operation
    • Generates events for capture by Internet Explorer or Visual Basic
    • Supports SSL, proxies, and multiple authentication mechanisms
    • Can be used from Internet Explorer (optional silent operation), Visual Basic or ASP

  • Visual upload and download controls
    • Upload and download GUIs work with XFile's file transfer engine
    • Can be used from Windows Internet Explorer, Visual Basic
    • Supports drag-and-drop
    • List of files to transfer can be preset
    • Accurate progress indicator

  • Server-side file transfers
    • Transfer files without user intervention
    • Perform cascaded uploads (client to server to server)
    • Transfer files from server to server

  • Receive files
    • Download multiple files to preset locations
    • Download to a string or to a file

  • Send files
    • Upload via RFC1867 Post (compatible with SoftArtisans FileUp™) or HTTP Put
    • Post a file, several files, and/or form elements

  • Multilingual support
    • SoftArtisans XFile is Unicode compliant, enabling the transfer of data between systems, regardless of language, without the risk of data corruption.

  • Easy to use Shell Extension allows uploads directly from Windows Explorer

  • Integration
    • Use in conjunction with SoftArtisans FileManager™ (included free with SoftArtisans XFile™) to preset files or manipulate files before or after transfer
    • Use with SoftArtisans Archive™ (included free with SoftArtisans XFile™) to compress files before or after transfer
    • Fully compatible with SoftArtisans FileUp™ to receive files on the server

*Most browsers are only capable of sending up to 2GB of data.


New Features

New in Version 5

  • Support for Windows Vista and Windows Server 2008 (as of version 5.1.1)
  • New Property for File object (as of version 5.0.2):
    • ClientChecksum: (read-only) Contains the MD5 checksum sent in the X-MD5 mime header for each file.
  • Full IIS 6 support (as of version 5.0) - New HttpModule is used in IIS 6 to overcome ASP.NET's inefficient memory utilization and to allow accurate progress indication.
  • Plus other fixes and enhancements. For details see Readme.htm in installation directory.
The new HttpModule is designed for the IIS 6 processing model, and replaces the ISAPI filter for ASP.NET applications. With the HttpModule, you will not have to run FileUp in IIS 5 isolation mode on an IIS 6 server.


System Requirements

FileUp Standard Edition
  • Windows 2000, XP, 2003, Vista, 2008, and 7

  • IIS 5 or higher

    In ASP.NET applications using the FileUp HttpModule (that is, all upload applications), IIS 7 is supported in classic .NET pipeline mode only.

  • ASP 5.0 or higher or ASP.NET 1.0 or higher

Supported Browsers for FileUp Standard Edition

FileUp supports all browsers that are compliant with the HTTP RFC1867 protocol for browser-based uploads and downloads. However, in order to use the XFile client-side ActiveX control, the client must use Microsoft Internet Explorer 4 and above, as Internet Explorer is the only browser with ActiveX support.


Frequently Asked Questions

  1. Can I use FileUp to upload pre-set files from my client?
  2. What versions of FileUp support ASP.NET?
  3. What other elements can I have on my form besides a file?
  4. What are the benefits of downloading with FileUp, rather than linking to the file directly?
  5. Why can't I use Request.Form in conjunction with an Upload?
  6. Can FileUp handle very large uploads?
  7. What is the HttpModule and when should I use it?
  8. Permissions and security: how should they be set for uploading?
  9. Can I encrypt files upon upload? Can I use SSL with FileUp?
  10. Can Fileup be used with ColdFusion for file uploads?
  11. How does FileUp compare to the Posting Acceptor?
  12. How can I capture additional fields when uploading?
  13. How does FileUp compare to FTP-based upload mechanisms?
  14. I rent virtual server space from an ISP running IIS. Can I just copy your dll to my site and start using it?

Can I use FileUp to upload pre-set files from my client?

If you are uploading from the broswer using an HTML form with a file input control (<input type="file">) you cannot pre-set the file path. This is a browser limitation which has nothing to do with FileUp. For security reasons, in order to prevent a malicious user from programmatically uploading a file from a user's system without their consent, browsers require the user to explicitly browse and select the file. Because FileUp is a server-side control, it is not capable of changing how the request is originally formed on the client.

The only way to programmatically send a pre-set file from a client machine to FileUp is to use an intelligent HTTP client that circumvents the use of the browser in forming the request. SoftArtisans offers the intelligent client, XFile, (an ActiveX control) that can be purchased separately or combined with FileUp Standard Edition as part of the FileUp Professional Edition product package. XFile provides visual and non-visual upload components that load in the browser for user-guided or invisible/automatic uploads. For specific technical information, see the documentation for each product.

What versions of FileUp support ASP.NET?

Version 4.0 is the first version of FileUp that provides support for ASP.NET (*.aspx) pages. FileUp 5.0 added .NET support for IIS 6 running in native mode. Not only was .NET support added, but additional functionality allows FileUp to bypass ASP.NET's significant upload size and memory utilization limitations, while offering advanced features such as progress indication. For more information on using FileUp in a .NET environment, see, Installing FileUp for ASP.NET, A Simple Upload in ASP.NET, Large Uploads in ASP.NET, Using FileUp with ADO.NET, and Scripting in C# in ASP.NET.

What other elements can I have on my form besides a file?

FileUp provides access to all form data.

What are the benefits of downloading with FileUp, rather than linking to the file directly?

Using FileUp to transfer files from the server to the client has several advantages over linking to a file directly:

  • Files downloaded with FileUp are more secure because:
    1. They do not need to be in a browsable location on the server.
    2. The path to the file only exists in the server-side code, which helps protect sensitive information from end-users.
  • Files can be downloaded from any location on the Web server, from a file server, or from a database.
  • FileUp also allows you to limit the bandwidth used for downloads per connection and per server.
Why can't I use Request.Form in conjunction with an upload?

Uploading is performed via an Internet standard called RFC 1867. This standard uses a different encoding scheme than typical HTML forms. Typically an HTML form may be defined as:

<FORM METHOD="POST" ACTION="PROCESS.ASP">

To upload files, an additional attribute must be specified:

<FORM METHOD="POST" ACTION="PROCESS.ASP" ENCTYPE="MULTIPART/FORM-DATA">

The ENCTYPE="MULTIPART/FORM-DATA" attribute changes the encoding type of the form to allow the efficient transfer of large amounts of data. However, the "MULTIPART/FORM-DATA" encoding type is not understood by the Request.Form property. It is unable to separate the file information from the other form data.

FileUp includes all of the Request.Form's functionality and can interpret forms using this alternate encoding scheme.

Can FileUp handle very large uploads?

FileUp can process upload requests of up to 4 GB in ASP.NET and 2 GB in ASP.

Permissions and security: how should they be set for uploading?

In ASP, to allow uploads, the IUSR_MACHINENAME or authenticated user must have Read, Write, and Modify NTFS permissions for FileUp's temporary and destination folders. An upload's destination folder is set in code by FileUp's Path property or SaveAsmethod.

In ASP.NET, if impersonation is disabled - as it is by default - FileUp executes in the context of the ASPNET account (Windows 2000, XP), NETWORK SERVICE (Windows 2003) or an authenticated user account. To allow uploads, the ASPNET account or authenticated user must have Read, Write, and Modify permissions for FileUp's temporary and destination folders. An upload's destination folder is set in code by FileUp's Path property or SaveAs method.

What is the HttpModule and when should I use it?

FileUp's HttpModule is an interceptor that is used under ASP.NET to overcome inefficient memory utilization in ASP.NET and in IIS 6, to allow accurate progress indication, and to allow uploads of up to 4-GB. The HttpModule intercepts an upload request, reads all the data, and writes it to a temp file chunk by chunk, before forwarding the request to ASP.NET.

Use the HttpModule in ASP.NET if you expect very large uploads and to display an accurate progress indicator.

Note that most browsers support uploads of up to 2-GB. Larger uploads must be generated by a client-side control that can handle very large transfers. FileUp Professional Edition (FileUpPE) includes a client-side file transfer control that can submit 4-GB uploads: SoftArtisans XFile [image].

For performance reasons, the HttpModule will not intercept all ASP.NET requests. Only requests for files with the extension .uplx will be handled by the HttpModule. Requests for files with the extension .aspx will not be processed by the HttpModule; they will be sent directly to ASP.NET. This prevents burdening the server with unnecessary use of the HttpModule.

For more information on the HttpModule, see Large Uploads in ASP.NET, Large Uploads in IIS 6, and Installing FileUp for ASP.NET.

Can I encrypt files upon upload? Can I use SSL with FileUp?

Files can be encrypted during transfer by using Secure Sockets Layer (SSL). If your server already is configured with a certificate, and you enable your Web application for use with SSL, then all transfers and uploads will encrypt files upon transfer. Use 'https:' instead of 'http:' in the URL.

SoftArtisans FileManager - included with FileUp - can encrypt a file after it is uploaded and saved on the Web server.

Can Fileup be used with ColdFusion for file uploads?

FileUp can be used in a ColdFusion application by using a ColdFusion Web form to submit the HTTP request containing files to be uploaded. However, FileUp depends on calls made to ASP or ASP.NET during the upload process, so it is typically instantiated in either an ASP or ASP.NET page. Following this scenario, the resulting response would show the name of the ASP/ASP.NET page in the url displayed in the browser's address window. If filename extension consistency is a concern, instead of generating an HTML response from this ASP/ASP.NET page, use Response.Redirect to redirect to a page with a .cfm extension. This .cfm page can be responsible for returning an appropriate response to the browser. Any variables that need to be passed to the new page can be added to a query string.

How does FileUpcompare to the Posting Acceptor?
  • ASP Integration: FileUpis fully scriptable by Active Server Pages. Rather than existing as a separate ISAPI DLL, FileUpintegrates very smoothly with your ASP application.
  • Standards support: PA Upload from IE browsers uses the proprietary WebPost API, rather than the standard RFC 1867, so by default you need different forms for Netscape and IE users.
  • Anonymous Connections: Since PA uses an ISAPI DLL, it must provide additional security protection outside of your ASP application. For this reason, PA disallows all anonymous connections. Since FileUpis integrated with ASP, your application can decide the appropriate level of security, including anonymous.
  • Control of the Upload: PA does not allow any control of the upload as it being sent. With FileUp, you limit the size of the upload, or decide at run-time to flush the upload. Best of all, you can change the location of the upload dynamically.
  • Processing: PA has a two-step upload and repost processing. With FileUp, everything can be accomplished in a single step, such as writing to a database depending on the status of the upload.
  • Uploading to a Database: Uploading to a Database: PA can only save uploads to disk. FileUp can save uploads to disk as well as to databases."
  • Price: PA is free. FileUpis not. Visit our Web site for the latest pricing. Site licensing and source code is available for FileUp.
How can I capture additional fields when uploading?

Instead of using the Request.Form object, use FileUp's form object which has identical functionality to Request.Form, but understands the different form encoding scheme used when performing file uploads.

How does FileUpcompare to FTP-based upload mechanisms?

FileUpoffers several advantages over FTP-based upload mechanisms:

  • Authentication : With FTP uploads, you must either manage a large number of user accounts or allow anonymous access. With uploads via a Web application, the application can determine who is allowed to upload, without a large administrative burden.
  • Security : Uploads using FileUpcan be SSL encoded so that the information is encrypted during transmission. There is no means for doing that using standard FTP.
  • Ease of configuration : FTP uploads require the administrator to fine tune NTFS permissions. With FileUp,this is determined by the application as well as by the administrator, if desired.
  • Flexibility : Want to save DOC files in one location and graphics in another? With FTP, your users have to know that. With FileUp,you can enforce these policies in your application and change them without disrupting your users.
  • Power : With FileUp,you can limit the size of the uploaded file dynamically every time it is invoked. You could even change the size depending on information contained in the same form. Additionally, you can flush uploads that do match certain criteria, such as wrong MIME type or file contents.
  • Simplicity and friendliness : An effective Web page can offer instructions, advise, on-line help. This is not possible with batch-based FTP. More importantly, with FileUp,when errors occur you can provide immediate feedback to the user and offer corrective action.
  • Firewall support : Many organizations do not allow out-bound FTP for security and intellectual property reasons. Since FileUpuses HTTP uploads, information can be transferred using HTTP Port 80 and will work with all modern firewalls and proxy servers.
  • Supplemental Information : FileUprenders accessible additional information about the upload, such as the user's original filename. This can be very useful in intranet scenarios.
  • Upload to a database : FileUpallows you to upload to an OLE DB database. Try that with FTP!
I rent virtual server space from an ISP running IIS. Can I just copy your dll to my site and start using it?

Your ISP must install FileUp on the server before you will be able to use it.


Related Products

Related Products from SoftArtisans

Industry-Standard File Transfer Technology

As the leader in HTTP-based file transfer technology, SoftArtisans has spent many years providing world-class products and services for both large corporations and individual developers seeking the secure, reliable and cost-effective delivery of business-critical data. Whether it's transferring multi-gigabyte files, providing flexible client-side functionality, or solving complex security and Web farm issues, SoftArtisans provides three different editions to meet your needs: FileUp Standard Edition, FileUp Professional Edition, and FileUp Enterprise Edition.

Delivering Business Information The Way You Want It

Now you can take customized Microsoft Excel and Word reports off your desktop and securely deliver them from a Web server to anyone and anywhere. Available for ASP and ASP.NET, SoftArtisans OfficeWriter is the first Web reporting product that utilizes the most popular content formats - Microsoft Excel and Word – to produce full-function, native Microsoft Office reports for distribution over the Web. This high-powered tool unites SoftArtisans ExcelWriter and WordWriter, allowing users to create, share and analyze crucial business data through both powerful spreadsheets and rich documents.


Before You Install

SoftArtisans FileUp is a COM component that offers optional support for ASP.NET, which is accomplished through the use of .NET interop code within a set of DLLs optimized for .NET. The following topics will help walk you through the process of decision making, identifying dependencies and and will teach you how to differentiate between the two sets of dlls.

Is the .NET framework installed on your webserver, or will you only need to support ASP?

FileUp requires different installation steps depending on whether or not you intend to use FileUp in .NET. This is because FileUp is a COM component that provides .NET support through an interop assembly. This interop support is dependent on the presence of the .NET framework. Because some users will continue to use FileUp in ASP only on servers that may not have the .NET framework installed, two sets of dlls are provided:

  1. In the FileUp\com directory: these dlls do not provide .NET support and are not dependent on the .NET framework.
  2. In the FileUp\dotnet directory: these dlls provide a .NET wrapper for use with the FileUp COM object. The .NET framework must be installed on the webserver in order for these dlls to properly function in .NET environments.
Automatic Installation:

During the Automatic Installation process, you will be asked if you want to install FileUp for ASP only or for both ASP and ASP.NET. In order for the installation to suceed for .NET support, the .NET framework must already be installed on the web server.

Regardless of whether you choose the ASP or the ASP.NET option during your install, both sets of dlls will be unpacked to your installation directory so that you may manually make changes to your configuration. If, for example, you later decide to install the .NET framework on your web server, add .NET support for your FileUp application by simply adding a reference in your ASP.NET application to the DLLs in the dotnet folder.

Previous versions of FileUp asked if you wanted to install FileUp in MTS/COM+. Recent editions of FileUp do not offer this option from the automatic installation because some users inadvertently installed FileUp in MTS/COM+ when they had not intended to do so. FileUp now is not installed in MTS/COM+ by default

Manual Installation:

Manual Installation requires that you first run the autoinstaller on a machine so that the dlls can be unpacked. After running the auto-installer the dlls can be copied onto the machine on which you would like to perform a manual install. Whether you are using FileUp in ASP or ASP.NET, register the files from the FileUp\com directory. Add references to the dlls that are in the FileUp\dotnet directory to your ASP.NET projects.

Identifying the Correct Dlls for the Support Required

Should you ever need to confirm that you are using the correct dlls, each dll file is labeled as to whether or not it contains .NET support. Right-click on the dll in question and choose "properties" from the context sensitive menu. Select the "version" tab. Under "Other Version Information", select "Comments" in the "Items" list. The associated value will contain the text "FileUp for .NET" if the dll contains .NET support. If the dll does not contain this text, it is the ASP-only version of FileUp.


Installing FileUp for ASP only

Installing FileUp for ASP

  • Upgrading to a New Version of FileUp
  • Automatic Installation
  • Manual Installation
  • Install Transactional Processing (Optional)

Upgrading to a New Version of FileUp

If you are upgrading to a new version of FileUp, remove the old version before installing the new version.

Automatic Installation

Before performing the automatic installation steps, please read the section Before You Install. This section will help you plan your responses to questions posed by the installer.

To run the automatic installer, double-click FileUp.exe and follow the InstallShield instructions.

The auto-installer will register the appropriate dlls in COM, as described in the "Manual Installation" section below. It will also set up samples in IIS. After running the auto-installer, please proceed to the Tailoring Your Installation chapter.

Manual Installation

Note: Before you can manually install FileUp on a server, you must run the auto-installer on another machine so that the dlls can be unpacked to the file system.

FileUp includes two sets of dll files in the folders COM and DotNet. The dlls in COM work only with ASP. The dlls in DotNet serve only as interop assemblies in ASP.NET. You should only register the dlls in the COM folder. For instructions on installing the ASP/ASP.NET version of FileUp, see Installing FileUp for ASP and ASP.NET.

To install FileUp the first time, run the automatic installation. Once InstallShield has unpacked the dll files that contain FileUp, you can re-install FileUp manually (if, for example, you are moving FileUp to a different server):

  1. Open a command prompt window and move to the directory FileUp\COM.
    For example, enter cd Program Files\SoftArtisans\FileUp\COM.

  2. Enter regsvr32 SAFileUp.dll. A dialog box will inform you that SAFileUp.dll registered successfully; click Ok.

  3. Enter regsvr32 SAPrgres.dll. A dialog box will inform you that SAPrgres.dll registered successfully; click OK.

  4. Enter iisreset to reset IIS.

The following table lists all .dll files included with FileUp. To use an optional file, register the file with regsvr32 (as explained above).

.dll File | Description
SAFileUp.dll | Required. SAFileUp.dll is the main component for uploading and downloading.
SAPrgres.dll | Recommended. SAPrgres.dll is FileUp's progress indicator.
SAFupps.dll | Optional. This dll is required for MTS/COM+ support only.
SAFupmon.dll | Optional. SAFupmon.dll contains FileUp's Performance Monitor counters.
SAArch.dll | Optional. SAArch.dll contains SoftArtisans Archive, a tool for creating and extracting ZIP and CAB archives.
SAFilmgr.dll | Optional. SAFilmgr.dll contains SoftArtisans FileManager, a file management tool.
SASmtp.dll | Optional. SASmtp.dll contains SoftArtisans SMTPMail, a full-featured SMTP e-mail client.

After manually registering the dlls, you should create registry keys as needed for your installation. Please proceed to Tailoring Your Installation:FileUp Registry Keys for a complete list of keys and appropriate default values.

Top

Install Transactional Processing (Optional)

To use transactional processing, run SAFileUpTXInstall.vbs:

  1. Copy SAFupps.dll, SAFileUpTXInstall.vbs, and SAFileUpTX.pak to any stable directory.

  2. From a command prompt window, navigate to the directory containing SAFupps.dll and register it by typing the command regsvr32 SAFupps.dll. You should see a dialog box telling you that SAFupps.dll registered successfully. Select OK to continue.

  3. Restart IIS by typing the iisreset command into the command prompt.

  4. From the command prompt window, run SAFileUpTXInstall.vbs, listing the path to SAFileUpTX.pak. For example, enter:

    CSCRIPT "C:\Program Files\SoftArtisans\FileUp\SAFileUpTXInstall.vbs" "C:\Program Files\SoftArtisans\FileUp"

Top


Installing FileUp for ASP and ASP.NET

Installing FileUp for ASP/ASP.NET

Step 1: Remove Prior Versions of FileUp

If you are upgrading to a new version of FileUp, before installing the new version, remove the old version.

Why do I need to remove the old version of FileUp?
FileUp is not a pure .NET assembly, so you cannot run differing versions side-by-side on the same webserver. Rather, FileUp is a COM component with an associated .NET interop assembly; therefore you can only have one version of the FileUp dlls installed (and registered in COM) on your webserver at any given time.
Step 2: Register the appropriate dlls in COM.
Option a: Automatic Installation

Before performing the automatic installation steps, please read the section Before You Install. This section will help you plan your responses to questions posed by the installer.

To run the automatic installation, double-click FileUp.exe, and follow the InstallShield instructions.

The auto-installer will register the appropriate dlls in COM, as described in the "Manual Installation" section below. It will also set up samples in IIS. After running the auto-installer, please proceed to the Tailoring Your Installation chapter.

Also, the auto-installer does not make FileUp available to .NET. You must follow additional instructions to make FileUp availabe to the .NET framework on an application or global level. Please see: Making FileUp Available to .NET Applications.

Option b: Manual Installation

To install FileUp the first time, run the automatic installation. Once InstallShield has unpacked the dll files that contain FileUp, you can re-install FileUp manually (if, for example, you are moving FileUp to a different server).

FileUp Specific dlls:

FileUp includes two sets of dll files in the folders COM and DotNet. The dlls in COM are only for direct use in ASP. The dlls in DotNet provide an interop assembly for use in ASP.NET and should not be installed on a server that does not have the .NET Framework. Most of FileUp's ASP.NET .dll files are not pure .NET assemblies; you must register the associated COM DLLs using regsvr32 before you can use them in .NET.

The following table lists all of the .dll files included with FileUp that require COM registration. To use an optional file, register the file with regsvr32(as explained above).

.dll File | Description
SAFileUp.dll | Required. SAFileUp.dll is the main component for uploading and downloading.
SAFupps.dll | Optional. This dll is required for MTS/COM+ support only.
SAFupmon.dll | Optional. SAFupmon.dll contains FileUp's Performance Monitor counters.
SAPrgres.dll | Recommended. SAPrgres.dll is FileUp's progress indicator.

The following dll is included with FileUp and as a pure .NET assembly should notbe registered in COM. It should instead be copied to your webserver for use in the configuration step "Making FileUp Accessible to .NET applications"

.dll File | Description
FileUpModule.dll | Optional, but recommended for .NET support. FileUpModule.dll contains the HttpModule. It is used to provide .NET support by intercepting the upload request before .NET caches the request to memory. This allows the upload to instead be cached to disk, thereby enabling very large uploads, increased upload request traffic or the use of FileUp's progress indicator. The HttpModule is a .NET assembly and does not require COM registration.

To register the FileUp specific dlls in COM:

  1. Open a command prompt window and move to the directory FileUp\COM.
    For example, enter cd Program Files\SoftArtisans\FileUp\COM.

  2. Enter regsvr32 SAFileUp.dll. A dialog box will inform you that SAFileUp.dll registered successfully; click OK.

  3. (Optional). To provide support for Progress Indication;
    Enter regsvr32 SAPrgres.dll. A dialog box will inform you that SAPrgres.dll registered successfully; click OK.

  4. (Optional). To provide support for performance monitoring;
    Enter regsvr32 SAFupmon.dll. A dialog box will inform you that SAPrgres.dll registered successfully; click OK.
    Note: This dll does not provide any functionality that would be included in your application, but is only used through the Windows Performance Monitor. Therefore, there will be no further information on the dll regarding making it available to your application in .NET.

  5. Enter iisreset to reset IIS.

The following dlls are distributed with FileUp as accessory components. These include the products File Manager, Archive and SMTPmail. These are COM components and do not provide any built-in .NET support. To be used in .NET, they must first be registered in COM and then an interop assembly must be generated with a tool such as Visual Studio.NET or the Type Library Importer (Tlbimp.exe) provided by the .NET Framework SDK. Each of these products can also be purchased separately and therefore have their own documentation set. The API documentation for each of these products is also included in the Programmers Reference section of this documentation

.dll File | Description | Documentation
SAArch.dll | Optional. SAArch.dll contains SoftArtisans Archive, a tool for creating and extracting ZIP and CAB archives. | Archive Documentation
SAFilmgr.dll | Optional. SAFilmgr.dll contains SoftArtisans FileManager, a file management tool. | File Manager Documentation
SASmtp.dll | Optional. SASmtp.DLL contains SoftArtisans SMTPMail, a full-featured SMTP e-mail client. | SMTPmail Documentation

After registering the appropriate dlls, at a minimum, you will need to create the FileUpTempDir registry key to specify the caching directory for the HttpModule. This key, as well as all of the optional keys are listed in Tailoring Your Installation: FileUp Registry Keys .

Step 3: Proceed to "Making FileUp Accessible to .NET Applications"
Now that FileUp has been installed in COM, you should proceed to "Making FileUp Accessible to .NET applications" to understand where and how to make FileUp available to .NET, including necessary edits to .NET config files.

Install Transactional Processing (Optional)

To use transactional processing, run SAFileUpTXInstall.vbs:

  1. Copy SAFupps.dll, SAFileUpTXInstall.vbs, and SAFileUpTX.pak to any stable directory.

  2. From a command prompt window, navigate to the directory containing SAFupps.dll and register it by typing the command regsvr32 SAFupps.dll. You should see a dialog box telling you that SAFupps.dll registered successfully. Select OK to continue.

  3. Restart IIS by typing the iisreset command into the command prompt.

  4. From the command prompt window, run SAFileUpTXInstall.vbs, listing the path to SAFileUpTX.pak. For example, enter:

    CSCRIPT "C:\Program Files\SoftArtisans\FileUp\SAFileUpTXInstall.vbs" "C:\Program Files\SoftArtisans\FileUp"

Top


Removing FileUp

Removing SoftArtisans FileUp

Automatic Removal

If FileUp was installed with the automatic installer, use Add/Remove Programsto unregister and remove FileUp and all of its associated documentation and samples:

  1. From the Start menu, select Settings -> Control Panel.
  2. Double-click Add/Remove Programs.
  3. Select SoftArtisans FileUp.
  4. Click the Change/Remove button to remove the old copy of FileUp.

Manual Removal

If FileUp's .dll files were manually registered with regsvr32, unregister the .dll files and delete them. Unregister either the COM version of the dlls or the dlls that offer .NET support, depending on what was originally registered on the machine. If the dlls were registered via the auto-installer, simply unregister the dlls in the FileUp root folder.

To manually remove FileUp:

  1. Unregister the dll Files from either FileUp or FileUp/COM, depending on which dlls were originally registered.
    1. Open a DOS prompt window.

    2. Navigate to the directory where the registered dlls reside.

    3. Enter regsvr32 SAFileUp.dll /u and click Ok.

    4. Enter regsvr32 SAPrgres.dll /u and click Ok.

    5. Enter regsvr32 SAFupps.dll /u and click Ok.

    6. Enter regsvr32 SAFileMgr.dll /u and click Ok.

    7. Enter regsvr32 SASmtp.dll /u and click Ok.

    8. Enter regsvr32 SAArch.dll /u and click Ok.

    9. To reset IIS, enter iisreset.

  2. Delete all copies of these files:
    • SAFileUp.dll
    • SAPrgres.dll
    • SAFupps.dll
    • SAFileMgr.dll
    • SASmtp.dll
    • SAArch.dll

  3. If you installed FileUp in the Global Assembly Cache, you must remember to remove the ASP.NET Assemblies from the GAC
    Installation in the GAC was optional. If SAFileUp.dll, SAPrgres.dll and FileUpModule.dll files are not in the GAC, go to step 5.

    1. Open a DOS prompt window.

    2. Go to FileUp's DotNet directory.

    3. Enter gacutil.exe /u SAFileUp.dll and click Ok.

    4. Enter gacutil.exe /u SAPrgres.dll and click Ok.

    5. Enter gacutil.exe /u FileUpModule.dll and click Ok.

    6. Delete the following line from the machine.config file from under the <assemblies>
                    node:

<add assembly="SaFileUp, Version=v5.3.1,
Culture=neutral, PublicKeyToken=f593502af6ee46ae"/>

<add assembly="SAPrgres, Version=fu.version.progress.build$,
Culture=neutral, PublicKeyToken=f593502af6ee46ae"/>

    7. Delete the following lines from the machine.config file from under the <httpHandlers> node:

      <add verb="GET,HEAD,POST" path="*.uplx"
      type="System.Web.UI.PageHandlerFactory" />
    8. Delete the following line from the machine.config file from under the <httpModules> node:

      <add name="FileUpModule" type="SoftArtisans.Net.FileUpModule,
      FileUpModule, Version=fu.version.module.build,
      Culture=neutral, PublicKeyToken=f593502af6ee46ae" />
    9. If you are running FileUp on Version 2.x of the .NET framework, delete the following lines from the machine.config file from under the <buildProviders> node:

      <add extension=".uplx" appliesTo="Web"
      type="System.Web.Compilation.PageBuildProvider" />

  4. If you installed FileUp in COM+ to use transactional processing, remove FileUp from COM+:

    Automatic Removal from COM+
    1. In Windows Explorer, go to the FileUp program folder (usually, C:\Program Files\SoftArtisans\FileUp).
    2. Double-click SAFileUpTXUnInstall.vbs.
    Manual Removal from COM+
    1. From the Start menu, go to Settings\Control Panel\Administrative Tools\Component Services.
    2. Open Component Services\My Computer\COM+ Applications
    3. Right-click the FileUp package, and select Delete.


Backwards Compatibility

The FileUp ISAPI filter

The FileUp ISAPI filter was introduced in version 4 of FileUp as a solution for overcoming upload limitations in the ASP.NET environment. The filter was designed for use with version 5 of IIS. With the introduction of IIS 6, there was no longer support for Read_Raw_Data ISAPI level filters in the native processing model. To address this incompatibility with IIS 6 the same pre-processing functionality that was available in the ISAPI filter was made available in the FileUp HttpModule. The HttpModule provides the same functionality as the ISAPI filter, but is compatible with both IIS 5 and IIS 6. As such, the ISAPI filter is now considered a deprecated technology.

If you intend to support legacy applications that use the ISAPI filter, you should be aware of the following:

  • A legacy application employing the ISAPI filter cannot be moved to an IIS 6 server, unless you are able to run that server in IIS 5 isolation mode.

  • In order to access documentation that provides instructions for use of the ISAPI filter, you will need to download version 5.0 of the FileUp docs.

  • The last version of the ISAPI filter was available in versions 5.0.14 of FileUp.

JFile

JFile was discontinued after the version 3 release (2004). If you are supporting a legacy application that uses JFile, samples were available in the FileUp documentation through the 5.0 release of the FileUp documentation. JFile samples can also be downloaded from the SoftArtisans Sample Code page.


Tailoring Your Installation

  • FileUp Registry Keys
  • Script Timeout
  • Session Timeout
  • Upload Read-Ahead
  • Locked File Retry Time
  • ASP.NET Settings
  • Performance Monitor Counters
  • Disabling FileUp Features


FileUp Registry Keys

Registry Settings For FileUp

These registry settings can be set or created at the following registry location:

HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\SA-FileUp\Parameters

Key | Type | Default Value (auto-installer) | Purpose
DisableTransferFile | REG_DWORD | 0 | Disables the TransferFile method of FileUp. 0 enables TransferFile. 1 Disables TransferFile.
DynamicAdjustScriptTimeout | REG_DWORD | 0 | If this key is set to 1, IIS's ScriptTimeout value will be increased until an upload or download is complete. Disable this feature by setting it to 0.
FileUpTempDir | REG_SZ (String) | Value of System Temp variable that is detected at installation, such as C:\WINDOWS\TEMP | Specifies the directory to which the HttpModule should cache an upload request.
LockedFileRetryTime | REG_DWORD | 45 | Sets the maximum number of seconds that FileUp will try to overwrite a file that is locked by another process.
MaxBytes | REG_DWORD | 0 | Specifies the maximum number of bytes on a per file basis that the HttpModule will write to disk before passing on the request for further processing. Setting this key to 0 disables MaxBytes. When using ASP or ASP.NET without the HttpModule, use the MaxBytes property of the FileUp object. When using the HttpModule, you must use this registry setting instead, since the HttpModule processes the request before the ASP.NET script is executed.
MaxBytesToCancel | REG_DWORD | 0 | Specifies the maximum size in bytes of the entire Request before the HttpModule will abort the Request.Setting this key to 0 disables MaxBytesToCancel. When using ASP or ASP.NET without the HttpModule, use the MaxBytes property of the FileUp object. When using the HttpModule, you must use this registry setting instead, since the HttpModule processes the request before the ASP.NET script is executed.
OnlyAllowVirtual | REG_DWORD | 0 | Of the methods that allow you to save files, this key allows only the SaveInVirtual method. Setting this key to 1 disables .Save and .SaveAs. Setting this key to 0 allows all methods to be used.
ISAPITempDir | REG_SZ (String) | Value of System Temp variable that is detected at installation, such as C:\WINDOWS\TEMP | Sets the caching directory of the deprecated ISAPI filter.


Script Timeout

ASP's ScriptTimeout property sets the length of time in seconds that ASP pages will allow for a script to execute. The default value of this property in IIS is 90 seconds. In a file upload, the ASP page must execute for the duration of the upload. If your user is transferring information over a slow line or is transferring a large quantity of information, it is easy to exceed this limit.

To increase the ASP ScriptTimeout in IIS:

  1. Right-click the application that will perform uploads, and select Properties.

  2. Select the Virtual Directory tab and click Configuration.

  3. Select App Options.

  4. In ASP Script Timeout, enter a value in seconds.

To increase the ASP ScriptTimeout in script, set the property Server.ScriptTimeout. For example:

<% Server.ScriptTimeout = 300 %>

The FileUp registry key DynamicAdjustScriptTimeout allows you to ensure that large uploads and downloads will not be timed out. If this key is set to True, IIS's ScriptTimeout value will be increased until an upload or download is complete.

To enable DynamicAdjustScriptTimeout:

  1. Open the Start menu and select Run...

  2. Enter regedit and click Ok.

  3. Open the folder HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\SA-FileUp\Parameters.

  4. Double click DynamicAdjustScriptTimeout. An Edit DWORD Value dialog will open.

  5. In the Value Data field, enter 1.


Session Timeout

In addition to the Script Timeout, IIS also maintains a session timeout. If the user has not requested a new page within a given number of minutes, ASP will cancel the session and release any resources associated with the session. If a user is in the process of uploading a file, it is possible that the transfer will be aborted.

It is recommended you set the Session timeout to be larger than or equal to the Script Timeout. The Script Timeout is measured in seconds. The Session Timeout is measured in minutes.

Note: You need be concerned with the Session Timeout only if you have Session state enabled on your server or on your specific web application.

To set the Session Timeout:

You can set the Session Timeout in the following two ways:

  1. On a per-session basis, you can set the Session Timeout by ASP Scripting Code.
  2. For all scripts, you can set the default system-wide.

By ASP Script:

Use the Session.Timeout property within your ASP script. For example:

<% Session.Timeout = 60 %>

System Default in IIS3:

Edit the Registry using REGEDT32. Modify the following value:

HKEY_LOCAL_MACHINE\

SYSTEM\

CurrentControlSet\

Services\

W3SVC\

ASP\

Parameters\

SessionTimeout

Double-click this value, and set the Radix to decimal. You can now enter an appropriate value in minutes. For example, 60 minutes is equivalent to one hour.

System Default in IIS 4 or later:

Using the Microsoft Management Console, select your web application that will perform uploads. Right-click to select the properties. From the Properties dialog, click on the "Configuration" button. Choose the "App Options" tab. Assuming that Session State is enabled, set the "Session Timeout" to the desired number of minutes. For example, 60 minutes is equivalent to one hour.


Upload Read-Ahead

If you anticipate large uploads, increase IIS's UploadReadAhead value to enable faster tranfers. UploadReadAhead is an IIS parameter that contains the amount of data that the server will read before passing control to the application. The application is then responsible for reading the rest of the data. The default UploadReadAhead is 48kb.

A high UploadReadAhead will enable faster transfers, but your uploads will utilize more physical memory. If you increase the UploadReadAhead value, increase the amount of RAM on the server as well.

To increase the UploadReadAhead value,

  1. Go to Start\Run
  2. Enter regedt32 to open the registry
  3. Open,
    HKEY_LOCAL_MACHINE\    SYSTEM\        CurrentControlSet\
                     Services\                W3SVC\
                             Parameters\
                                 UploadReadAhead

  4. Highlight the UploadReadAhead value (in the right frame)
  5. Open Edit and select DWORD
  6. Enter a new value in the Data window

If the UploadReadAhead parameter does not exist in your registry, you can add it. To add the parameter,

  1. Open the Edit menu
  2. Select Add Value
  3. Enter "UploadReadAhead" in Value Name
  4. Enter REG_DWORD in Data Type
  5. Click Ok
  6. Enter the value in kb


Locked File Retry Parameter

Locked File Retry Time Parameter

SoftArtisans FileUpis frequently used to upload content to a virtual directory of a web site. Once the content has been requested via HTTP, IIS or some other process may lock the file containing the content. For example, a user uploads a GIF file, and then immediately views the uploaded GIF in her browser. The user then tries to immediately upload a replacement GIF file. With versions 4 and later of IIS, this upload will fail. These versions lock static content files (e.g., GIF, HTML) for as long as 30 seconds after they are requested by HTTP. Additionally, versions 4 and later of IIS will continue locking the content file for as long as there are outstanding requests to that file. A heavily requested file may stay locked for minutes or hours at a time.

Other processes on a web server, such as content indexing, backup utilities, or virus scanners, may also lock the files. FileUpwill retry overwriting the locked file once per second for up to 45 seconds.

Via the Registry, it is possible to set the default number of seconds that FileUpwill re-attempt overwriting the locked file.

In HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\FileUp\Parameters, LockedFileRetryTimesets the maximum of number of seconds to retry overwriting a locked file before failing.

References: Microsoft Knowledge Base articles Q191742 and Q182626.


ASP.NET Settings

In the .NET configuration file for your Web application - web.config or machine.config- there are several attributes that can affect the performance of large uploads. To set these attributes at the machine level, modify machine.config (located in [windows directory]\Microsoft.NET\Framework\[.NET Version Directory]\CONFIG). To set the attributes at the application level, modify your application's web.config file.

You will find the following values in the httpRuntime node of machine.config:

  • executionTimeout
    Time in seconds before a request is timed out.

  • maxRequestLength
    Maximum request size in kilobytes that ASP.NET will accept.

  • appRequestQueueLimit
    Maximum number of requests queued for an ASP.NET application. The default value of appRequestQueueLimit is 100. If your server will be handling more than 100 concurrent requests, increase the value of appRequestQueueLimit.

The following attributes are in the processModel node of machine.config:

  • responseDeadlockInterval
    Specifies the time interval, in the format HH:MM:SS, after which the process will be restarted if the following conditions are met:
    • There are queued requests.
    • There has not been a response during this interval.
    The default value of responseDeadlockInterval is 3 minutes. To allow very large uploads, you may have to increase this value. This property must be set in machine.config, not at the application level in web.config. It will affect any response deadlock in ASP.NET and should be used with caution.

  • responseRestartDeadlockInterval

    • Specifies the time, in the format HH:MM:SS, that must elapse after the last restart to cure a deadlock before the process is restarted to cure a deadlock again. This prevents thrashing on processes that require a relatively long startup time. The default value of responseRestartDeadlockInterval is 9 minutes. To allow very large uploads, you may have to increase this value. This property must be set in machine.config, not at the application level in web.config. It will affect any response deadlock in ASP.NET and should be used with caution.

  • maxIoThreads

    • Maximum number of IO threads per CPU in the thread pool. The default value of maxIoThreads is 25. Increasing this value will increase the number of concurrent executing requests, significantly reducing the amount of time it takes to process concurrent requests. This value is particularly important for large uploads using the HttpModule. If you expect many concurrent uploads to your site, you should set maxIoThreads to the number of concurrent uploads that you wish to support.

Top


Performance Monitor Counters

FileUphas the ability to add counters to the Performance Monitor to more carefully monitor the usage and success rate of FileUp.

To use the Performance Monitor Counters:

  1. Go to Start... Programs... Administrative Tools (Common)... Performance Monitor.
  2. Once you are in the Performance Monitor program, choose Edit... Add to Chart (Ctrl+I).
  3. Select Softartisans FileUpwithin the Object combo box.
  4. Choose the individual counters you wish to monitor.

The following table lists the individual counters:

Performance Counter | Displays
Aborted Transactional Uploads | The number of transactional uploads that have been aborted.
Average Download Duration | The average duration for all downloads.
Average Upload Duration | The average duration for all uploads.
Canceled Downloads | The number of downloads that have been canceled.
Canceled Uploads | The number of uploads that have been canceled.
Committed Transactional Uploads | The number of transactional uploads that have been successfully committed.
Successful Downloads | The number of successful downloads.
Successful Uploads | The number of successful uploads.
Total Bytes Downloaded | The total number of bytes downloaded.
Total Bytes Uploaded | The total number of bytes uploaded.
Total Download Duration | The total duration for all downloads.
Total Upload Duration | The total duration for all uploads.


Disabling FileUp Features

Disabling SoftArtisans FileUp Features

SoftArtisans FileUpallows an ISP or sophisticated web administrator to disable specific FileUpfeatures via the registry.

There are several registry settings that can be used to disable certain features. By default, all features are enabled. Setting a value to '1' in the registry will disable that particular feature.

  • In HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\SA-FileManager\Parameters
    • DisableACL disables all ACL modifications.
    • DisableLogonUser disables the LogonUser method.
    • DisableRegisterDLL disables registration of DLLs.
    • DisableDelete disables the FileManager.DeleteFile, File.Delete, and FileUp.Delete methods, preventing file deletion. It is still possible to use the FileUp.Delete method without any parameters to delete the currently uploaded file. This registry entry prevents deletion of any arbitrary file from the file system.

  • In HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\FileUp\Parameters
    • DisableTransferFile disables the TransferFile / File Download function.
    • OnlyAllowVirtual allows only the SaveInVirtual method. Disables .Save and .SaveAs.


Making FileUp Available to .NET Applications

  • Making FileUp Available to ASP.NET for Application Level Accessibility
  • Making FileUp Globally Available to .NET Applications


Application Level Availability

Making FileUp available to ASP.NET for Application Level Accessibility

Before making FileUp available to .NET applications, you must first start by following the directions for installing FileUp for ASP.NET.

Step 1: Add the appropriate FileUp dlls to the bin directory of the application.
The following dlls need to be added to the bin directory of your .NET application:
.dll File | Description
SaFileUp.dll | Includes the built-in interop support
SAPrgres.dll | (Optional). If you chose to provide support for Progress Indication by registering the SAPrgres.dll file in COM, you must also make this dll available to .NET
FileUpModule.dll | (Optional). It is recommended that your .NET FileUp application utilizes the HttpModule to overcome .NET performance limitations. Make the HttpModule available by placing the FileUpModule.dll file in the bin directory of your application.

The dlls can be added to the bin directory manually by simply copying the dlls to the bin. If you are using Visual Studio to develop your application, you should add the dlls as a reference to your project. This will automatically copy them to the bin folder of your application as well as make them available to the project during development. Please note that you must click the "Browse..." button in the Add Reference dialog and navigate to them in the FileUp\dotnet directory. They will not be listed in the .NET tab."

Step 2: Update the web.config file for the application.
Under the <configuration> ... <system.web>node in the web.config, update as instructed below.

(Optional). If you chose to implement the (recommended) HttpModule, you must add the following to the web.config file under the <configuration>and <system.web> nodes:

<httpModules>
<add name="FileUpModule" type="SoftArtisans.Net.FileUpModule,
FileUpModule, Version=$fu.version.module.build$, Culture=neutral,
PublicKeyToken=f593502af6ee46ae"/>
</httpModules>
<httpHandlers>
<add verb="*" path="*.uplx"
type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>

If you are running FileUp on version 2.x of the .NET Framework, your web.config changes to support the module will also include additions to the <compilation> node:

<compilation>
<buildProviders>
<add extension=".uplx"
type="System.Web.Compilation.PageBuildProvider"/>
</buildProviders>
</compilation>
<httpModules>
<add name="FileUpModule" type="SoftArtisans.Net.FileUpModule,
FileUpModule, Version=$fu.version.module.build$, Culture=neutral,
PublicKeyToken=f593502af6ee46ae"/>
</httpModules>
<httpHandlers>
<add verb="*" path="*.uplx"
type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>
Step 3: Instruct IIS to pass .uplx requests to ASP.NET for processing.

If you chose to add support for the HttpModule, you must also instruct IIS to allow ASP.NET to process files with the .uplx extension. The HttpModule intercepts requests to files with the extension .uplx. After a request is handled by the HttpModule, the request needs to be forwarded to ASP.NET.

Add .uplx to the Application's App Mappings
  1. Open IIS, right-click your application's virtual directory, and select Properties.

  2. Select the Virtual Directory tab.

  3. Click Configuration.

  4. Select the App Mappings tab.

  5. Click Add.

  6. Browse to aspnet_isapi.dll (typically in [Windows directory]\Microsoft.NET\Framework\[.NET version directory]\).

  7. In the Extension field, enter .uplx.

  8. Select All Verbs.

  9. Check Script Engine, and click OK.

Properly configured application mappings for the .uplx extension:

Top


Global Availability

Making FileUp Globally Available to .NET applications

Before making FileUp available to .NET applications, you must first start by following the directions for installing FileUp for ASP.NET.

Step 1: Add the appropriate FileUp dlls to the Global Assembly Cache (GAC)

To make FileUp available to any .NET application, server-wide, add the following dlls to the GAC.

  1. Open a command prompt window and move to the directory FileUp\Dotnet.
    For example, enter cd Program Files\SoftArtisans\FileUp\Dotnet.

  2. Enter gacutil /i SAFileUp.dll.

  3. (Optional) If you chose to provide support for Progress Indication by registering the SAPrgres.dll file in COM, you must also make this dll available to .NET:
    Enter gacutil /i SAPrgres.dll.

  4. (Optional) It is recommended that your .NET FileUp application utilizes the HttpModule to overcome .NET performance limitations. Make the HttpModule available by setting up the FileUpModule.dll file in the GAC:
    Enter gacutil /i FileUpModule.dll

Step 2: Update the Machine.Config file.
  1. Open the file machine.config (located in [Windows directory]\Microsoft.NET\Framework\ [.NET version directory]\CONFIG).

  2. Add the following lines to the assemblies node of machine.config:

    <add assembly="SaFileUp, Version=v5.3.1,
    Culture=neutral, PublicKeyToken=f593502af6ee46ae"/>
    <add assembly="SAPrgres, Version=$fu.version.progress.build$,
    Culture=neutral, PublicKeyToken=f593502af6ee46ae"/>

    The version attribute must correspond exactly to the version of SaFileUp.dll that you added to the GAC. To get the exact version of SaFileUp.dll, right-click the file and select the Properties tab, and check the File version (not the Product version).

  3. (Optional)If you chose to add support for the HttpModule, add the following line
                            to the httpHandlers node of machine.config:

<add verb="GET,HEAD,POST" path="*.uplx"
type="System.Web.UI.PageHandlerFactory" />

Add the line above to machine.config before these entries:

<add verb="GET,HEAD" path="*"
type="System.Web.StaticFileHandler" />
<add verb="*" path="*"
type="System.Web.HttpMethodNotAllowedHandler" />
  4. (Optional)If you chose to add support for the HttpModule, add the following to the httpModules node of machine.config:

    <add name="FileUpModule" type="SoftArtisans.Net.FileUpModule,
    FileUpModule, Version=$fu.version.module.build$, Culture=neutral,
    PublicKeyToken=f593502af6ee46ae"/>

    The version attribute must correspond exactly to the version of FileUpModule.dll that you added to the GAC. To get the exact version of FileUpModule.dll, right-click the file and select the Properties tab, and check the File version (not the Product version).

  5. (Optional) If you are using the 2.x version of the .NET Framework and you chose to add support for the HttpModule, you must also add the following to machine.config:
    <compilation>
    <buildProviders>
    <add extension=".uplx"
    type="System.Web.Compilation.PageBuildProvider"/>
    </buildProviders>
    </compilation>
Step 3: Instruct IIS to pass .uplx reqeusts to ASP.NET for processing.

If you chose to add support for the HttpModule, you must also instruct IIS to allow ASP.NET to process files with the .uplx extension. The HttpModule intercepts requests to files with the extension .uplx. After a request is handled by the HttpModule, the request needs to be forwarded to ASP.NET.

In the Windows XP IIS console, the Web Sites and Web Site nodes have identical properties dialogs. The script maps can be installed in the Web Sites properties, but they will be ignored by IIS. The script maps must be installed from the Web Site node.
Add .uplx to the Web Site's App Mappings
  1. Open IIS, right-click the Web Site, and select Properties.

  2. Select the Home Directory tab.

  3. Click Configuration.

  4. Select the App Mappings tab.

  5. Click Add.

  6. Browse to aspnet_isapi.dll (typically in [Windows directory]\Microsoft.NET\Framework\[.NET version directory]\).

  7. In the Extension field, enter .uplx.

  8. Select All Verbs.

  9. Check Script Engine, and click Ok.

Properly configured application mappings for the .uplx extension:

Top


Configuration and Application Planning for ASP

  • Understanding the Concepts: Client vs. Server
  • Permissions, Caching and Saving
  • Production Notes


Understanding the Concepts: Client vs. Server

Understanding the Concepts

Client vs. Server: Understanding what functions where in a web application designed with SoftArtisans file transfer products

FileUp Standard Edition:

FileUp is a server-side component. It installs on the web server as a package of dlls that add the ability to parse through an upload request containing files with or without additional form elements. FileUp is instantiated in server-side script, such as in ASP or ASP.NET. It is designed to accept and RFC-1867 compliant HTTP post. It is not dependent on any specific client, rather it is dependent on receiving a properly formatted POST. Any client that can send an RFC-1867 compliant post is acceptable, whether it is a browser, ActiveX control or applet.

The only visual component to FileUp is the optional progress indicator, which shows "server-side" progress, meaning the progress of the processing of an upload after the request has already reached the server.

What can I use as the client?

Anything that can send an RFC 1867-compliant HTTP post, such as the browser, an ActiveX control or applet can be used as a client.

What do the FileUp Standard Edition samples use as the client?

The FileUp Standard Edition samples use a "MULTIPART/FORM-DATA" encoded HTML form to post the upload request. Therefore, any browser can be used, such as Internet Explorer, Netscape or Firefox, provided that these browsers continue to support the RFC-1867 standard. (For an example of using an active x control as a client, see FileUp Professional Edition.)

Because FileUp is a server-side component, it cannot control any client-side behavior.It can only affect the upload request after it has reached the server.

What are the practical design considerations of this approach?

  • For every file you want to upload, you must provide an HTML input control of the type "file".
  • The user cannot select directories, but rather can only select one file for every control that is available.
  • HTML file input controls cannot be pre-populated via script. The user must select the file.
  • HTML file input controls provide very little control over their appearance.
  • Most browsers have a maximum upload request size limitation of 2 GB.
  • You will not be able to script any limitations on the upload request, such as types of files to be uploaded, or sizes of files. Any limitations that you want to provide need to happen server-side, after the files have already been received on the server.
  • The browser can download only one file per request.
  • All of the common browsers support HTML forms.
  • No additional software needs to installed client-side, other than the browser.

FileUp Professional Edition (FileUpSE + XFileSE)

FileUp Professional Edition is a package that includes FileUp Standard Edition in addition to XFile Standard Edition. FileUp Professional Edition differs from Standard Edition in that both client-side and server-side solutions are provided.

FileUp on the server:
(see description for FileUp Standard Edition)

XFile as the client:
FileUp requires that the client send an RFC-1867 compliant post. While this can be achieved using the browser and an HTML form, there are certain design limitations, as described above (link to a bookmark at FileUp SE: “What are the practical design considerations of this approach?�?)

XFile is an ActiveX control that can be distributed automatically from your web server, but installs and functions client-side. XFile is instantiated in an HTML object tag in the browser. Even though the browser is required to render the HTML and load XFile as a control, XFile is used as the client instead of the browser. XFile is responsible for sending the Request and receiving the Response.

In addition to circumventing the browser, XFile provides a programmable interface and an optional Graphical User Interface (GUI).

What are the design considerations of this approach?

  • Active X is currently only supported by Internet Explorer
  • XFile provides a rich set of functionality, including the ability to upload folders, multiple files, programmatic control of the user’s visual experience, programmatic control of the types, sizes and amount of files. For a complete list of features supported by XFile, please see: [link to XFile feature list]
  • Upload limit of 2 GB; however smaller limits can easily be enforced before the request is even sent. XFileEE can be used in conjunction with FileUpEE {insert link here} to overcome this limitation.


Permissions, Caching and Saving

  • Planning for Caching, Saving and Transferring
  • Default Directory for Cached Files
  • Understanding Permissions
  • Special Permissions: Uploading to a Network Share


Planning for Caching, Saving and Transferring

Planning Permissions for Caching, Saving and Transferring (ASP)

Plan for a Cache Location

In ASP, FileUp requires a directory to which to cache an upload provided that FileUp's UseMemoryproperty is set to "false". (This is the default value.) The caching directory does not need to be exposed as a virtual directory. For security reasons, it may be best to purposely avoid caching to a directory that is also exposed as a virtual directory.

Once the directory is chosen, you must provide appropriate NTFS permissions so that FileUp can access this directory. This directory requires "Read", "Write" and "Modify" permissions for the identity assumed by your web application.

To inform the FileUp object where it should cache, please see the topic Default Directory for Cached Files

Under What Identity will the Caching Occur?

In ASP, the identity is determined by the following:

  • The identity assumed by FileUp is the identity of the web application as set in IIS. The default account for anonymous authentication is the IUSR_[machine_name] account. The two exceptions to this behavior are described in the next two bullets.

  • If FileUp is installed in COM+ as a server package with a specified identity, this is the identity that takes precedence.

  • If the FileUp script changes page-level identity (before caching) by calling FileManager's LogOnUser method, this is the identity that will be used, unless FileUp is installed in COM+ as described above.

Plan for a Save Location

FileUp requires a location to which the uploaded files should be saved. This can be the same directory as was choosen for a caching location, it may be a different directory or directories, or it may be a database.

Once the directory or directories are choosen, you must provide appropriate NTFS permissions so that FileUp can access this directory. To save to a directory, the identity under which FileUp is running requires "Read", "Write" and "Modify" permissions. If you are saving to a file-based database, such as Microsoft Access, you need to provide "Read" and "Write" permissions to this identity for the directory in which the file-based database resides.

Under What Identity will the Saving Occur?

In ASP, the identity is determined in the same way as it is for caching.

For more information on where to set the save paths in your application, please see the Programmer's Reference for the following property and methods:[FileUp].Path, [FileUp| File].Save, [FileUp| File].SaveAs, [FileUp| File].SaveAsBlob, [FileUp].SaveBinaryAs, [FileUp].SaveRecursiveand [FileUp| File].SaveInVirtual.

Downloading with FileUp's TransferFile method

The directories from which FileUp will be transferring files, will require NTFS "Read" permission, which is set in the same way as described in "Save Location". Identity is determined likewise.

For more information on where to set the path from which files should be downloaded, please see the Programmer's Reference for the following methods [FileUp].TransferFile and [FileUp].TransferBlob.


Default Directory for Cached Files

For the FileUp Object (ASP)

When you upload a file to the server, it is cached before you save it. On an ASP page, you can specify where you want to cache the file on the server, using SoftArtisans FileUp's Path property . The Pathproperty must be set before the script references any form elements, which would force the upload to be cached. The timing of caching is explained in more detail in the topic Understanding Permissions.

<%
Dim fileUpload
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")
fileUpload.Path = “C:\MyCachingDirectory�?
%>

If you do not assign a value to the Pathproperty, uploads will be cached in your system's default directory for cached files. Unless otherwise configured, the default directory is typically C:\winnt\tempor C:\temp. You can assign a different default directory for cached files by setting the TEMP environment as a system variable.

To set a default directory for cached files:

  1. Open the Control Panel.

  2. Select "System".

  3. Select the "Environment" tab.

  4. Activate the "System Variables" window by selecting one of the variables within it.

  5. At the bottom of the "Environment" window are two text boxes: "Variable" and "Value". In "Variable", enter TEMP. In "Value", enter the path you want to set as the default for cached files.


Understanding Permissions

Understanding Permissions for FileUp
on the Web Server (ASP)

In the process of uploading a file with FileUp, your web application will be performing some basic file system tasks such as caching, saving and renaming that require you to understand NTFS permissions.

Understanding How FileUp Works

When an upload request is received on the server, FileUp has two responsibilities that may require interaction with the server's file system:

  • Caching the request to either the file system or to memory, so that it can parsed for form elements and files.
  • Providing a final destination for the files, either to the file system or to a database

In order to parse through an upload request, FileUp must be able to cache the request, either to disk or memory. Caching the upload request to disk requires "Read", "Write" and "Modify" NTFS permissions on the caching directory. Later, when FileUp is instructed to save the file, these same permissions are required on the directory to which the files will be saved.

When and where does the upload get cached?

In ASP

FileUp will cache the upload request as soon as any element of the upload request, such as a file or a form element, is called in the script. At that point, FileUp will check to see if its Path property has been populated. If it has, it will cache the upload request to this directory. Setting the path property before referencing any files or form elements is considered "best practice"; however, if the Path property has not yet been set to a valid path, FileUp will check the web server’s system TEMP variableand attempt to cache the upload request there.

The exception to this case is when the UseMemory property of FileUp is set to "true". The default value of UseMemory is "false", meaning the upload will cache to disk. If UseMemory is set to "true", FileUp will not cache to disk, but will instead cache to memory. Caching to memory requires neither a directory nor NTFS permissions. You will still however, need to understand how to set NTFS permissions on the directory to which the upload is finally saved, if you call “Save�? or “SaveAs�? on an uploaded file.

In the following code sample, you can see that following best practice, on Line 9, the Path property is set immediately after instantiating FileUp. By setting this property immediately after instantiating FileUp, you can be assured that FileUp will cache to the directory specified in the Path property. FileUp is forced to cache the upload when the first form element is accessed, at line 11, and because the path property has been set already, FileUp will cache to “C:\MyCachingDirectory�?.

Line 1: | '--- Declarations
Line 2: | Dim oFileUp
Line 3: | '--- Instantiate the FileUp object
Line 4: | Set oFileUp = Server.CreateObject("SoftArtisans.FileUp")
Line 5: | '--- Set the Path property to the location you wish to
Line 6: | '--- temporarily cache the incoming file before saving
Line 7: | '--- Note: This property should be set immediately after
Line 8: | '--- instantiating the FileUp object
Line 9: | oFileUp.Path = “C:\MyCachingDirectory�?
Line10: | '--- Confirm that the control “myFile1�? is a file input control
Line11: | If IsObject(oFileUp.Form("myFile1")) Then

When and where does the upload get saved?

If the Path property has been set to a valid directory, when the Savemethod is called on any file, the final saving directory will be taken from the Path property. If SaveAs is used in conjunction with a new directory path, that directory will be used instead. Should the Save method be called without having specified a path, FileUp will attempt to save the file(s) to the directory specified in the system TEMP variable.

Under what identity does FileUp run? To whom are the NTFS permissions granted?

NTFS permissions need to be granted to users or groups. You will therefore need to understand what identity FileUp assumes.

The default behavior of any object running in a web page is to assume the identity of the web application. Because you must be certain of the identity of FileUp in order to correctly set NTFS permissions, some less commonly used means of changing the identity of FileUp have been listed as well.

  1. FileUp executes under the same identity as your web application.
    This is the most common scenario. FileUp will assume the identity that is set for your web application. The default identity is the local IUSR account.

  2. SoftArtisans FileManager can be used to change identity of FileUp within the ASP code in a LogOnUser /RevertToSelf block.
    If caching or saving occurs within this block, FileUp will assume the identity specified in the LogOnUser method.

  3. COM+ can be used to specify the identity of the FileUp dll. If FileUp is installed in COM+ as a server package with a specified identity, this identity will be used. This takes priority over any web application settings or the use of FileManager's LogOnUser method.

How to Determine or Set Identity

Check the Identity of Your Web Application in IIS.
  1. Locate your web application in IIS.
  2. Right-click on the application directory, choose "properties".
  3. Select the "Directory Security" tab.
  4. In the section "Anonymous access and authentication control", click on the "edit" button. This tab lets you know what your current settings are for your application.

    • Anonymous Access
      If this box is checked, it means that all users will have anonymous access to your web application. This means that there is no authentication required and your web application will run as the user specified in the User Name text box.

      This dialog shows the username and password of the account used by your web application when anonymous access is granted. The default account is the IUSR account, "IUSR_[machine_name]" and the password is controlled by IIS. The IUSR account is a local account and a member of the group "guests". This account can be changed, but this has implications outside the scope of this tutorial. If you do decide to change this account, consult the documentation for IIS to determine what other actions need to be taken (for example, granting the right to “Log on locally�? to the new user account).

      Assuming that you do not change this account, the IUSR account is the account to which you must grant the appropriate NTFS permissions when FileUp is assuming the identity of your web application.

    • Basic Authentication/Digest Authentication
      If this box is checked, the user is prompted for a username and password when they access the site. If the username and password match an account recognized by the web server, then the user is granted access and the web application runs as that user's identity. In this situation that particular user, or a group to which this user belongs, must be given the "Read", "Write" and "Modify" permissions on the directory to which FileUp will cache or save.

    • Integrated Windows Authentication
      Checking this box assumes that the client will be on the same windows domain as the web server, which may be the case for an intranet application. The browser will pass the NT login credentials from the client machine to the web server for authentication. The web application will then run as this domain user. Integrated Windows Authentication only allows you to cache or save files to the web server. You will not be able to pass on the NT login credentials to another server, which is the case when you attempt to cache or save files to a network share. (For more information on saving files to a network share, please see Uploading to a Network Share .)

Change the identity of FileUp by using FileManager.

FileManager is distributed with FileUp. By calling FileManager’s LogOnUserand RevertToSelf methods, you can change FileUp’s identity within the ASP or ASP.NET script, without changing the identity of the entire web application in IIS. To be certain of FileUp’s identity, you should check your code for calls to FileManager’s LogOnUser/RevertToSelf methods. For more information on using LogOnUser/RevertToSelf, please see the FileManager Programmer's Reference

Confirm identity by using FileManager.

With any of these web application or page level means of setting identity (in IIS, in script with FileManager), you can confirm your understanding of the identity assumed by your web application by using SoftArtisans FileManager to report the identity with the CurrentUser property. For more information on the CurrentUserproperty and a code snippet, please see the FileManager Programmer's Reference.

Set FileUp's identity at the dll level with a COM+ server package installation.

Change the identity of FileUp by installing FileUp in COM+ as a server package with a specified identity. If FileUp is installed in COM+ as a server package, an identity can be specified. When the FileUp web application runs, it will run as the identity specified in IIS, but FileUp itself will run as the user specified in COM+. Because the identity is changing in the COM+ layer and not in the web application layer, tools such as FileManager’s CurrentUser property will not be able to report this identity switch. When troubleshooting identity problems, you will want to open the COM+ manager to see if FileUp’s identity is being changed by having been installed as a server package that runs as a specific account.

  1. Open the control panel
  2. Open “Administrative Tools�?
  3. Open “Component Services�?
  4. In Component Services, navigate to the “computers�? folder.
  5. Under the “computers folder�?, navigate to the “COM+�? folder
  6. Under the COM+ folder look for a package named “SA-FileUp�?.
  7. If the “SA-FileUp�? package exists, FileUp has been installed in COM+. Next, check to see if it is installed as a server or library package.
  8. Right-click on the package and choose “properties�?.
  9. In the properties dialog, choose the “Activation�? tab. The Activation type will be either “library�? or “server�?.
  10. If FileUp is installed as “library�? package, FileUp will assume the identity of the web application when it is run. If FileUp is installed as a server package, it is possible to specify a different identity for FileUp, regardless of web application settings. To check for a specified identity, select the “Identity�? tab.
  11. If an identity is specified, you will need to grant NTFS permissions on your caching and saving directories for this identity, even if the web application is set to a different identity.
  12. If the package is set to run as the “current logged on user�? then FileUp will continue to run as the identity specified for the web application in IIS.

Setting NTFS Permissions

Once both the identity of FileUp and the caching/saving locations have been determined, NTFS permissions can be set.

  1. Open Windows Explorer and navigate to the directories to which you will be instructing FileUp to cache or save.
  2. Right-click on the directory, choose “Properties�?.
  3. From the Properties dialog, choose the “Security�? tab.
  4. On the Security tab, you will see a list of users. Check to see if the identity FileUp will be running as is listed here.
  5. If the user is not listed, you will need to add the user, by clicking the “Add�? button.
  6. In the dialog to select users or groups, select the user that FileUp will be running as. For example, if you are using anonymous authentication with the default anonymous user account, select the local machine domain to obtain a list of local users, then select the user named “IUSR_[machine_name]�?. Click OK to return to the “Security�? dialog.
  7. Select the user that you just added to the security list. With this user selected, now set the following permissions: “Allow�? on “Read�?, “Write�? and “Modify�?.
  8. If the permissions cannot be changed, check to see if the “Allow inheritable permissions�? check box is selected. If it is, you will need to uncheck it in order to be able to change the permissions on this directory. You will want to make a note of the inherited permissions, as removing them may affect other applications. You will be prompted to either completely remove the inherited permissions or to copy the existing permissions. If you are uncertain of which action to take, copy the existing permissions and then add your FileUp user permissions in addition to your existing permissions.
  9. Click OK to apply and save your changes. Repeat this process for each directory to which FileUp requires access due to caching or saving activity.

Summary for setting appropriate permissions for FileUp in ASP

  1. Determine the identity of your web application.
  2. Determine the location where FileUp will cache the upload and provide "Read", "Write" and "Modify" NTFS permissions to this directory for your application identity.
  3. Determine the location where FileUp will save the upload and provide "Read", "Write and "Modify" NTFS permissions to this directory for you application identity.


Special Permissions: Uploading to a Network Share

Uploading to a Network Share

FileUp supports uploading to a network share, provided that the path is accessible to the user account under which your application is running. This needs to be considered in regards to the path itself as well as NTFS permissions to the directory.

When saving to a network share, there are a number of issues to be aware of with regard to the identity of your upload application (or the upload processing page). First of all, if your application or page is running under a local account such as the default anonymous acount (IUSR_MachineName) the upload will fail because this account does not have network priviledges. Windows Integrated Authentication is also not an option because IIS will not pass the credentials to the networked server. Therefore, one of the following approaches must be used.

UNC Paths vs. Mapped Drives

Mapped drives are dependent on user profiles. If you intend to use a mapped drive in your FileUp script, you must be certain that the mapped drive is available to the user account under which your application is running. A UNC style path is not dependent on user profiles and is a better solution when application identity varies.

Using an account that has NTFS persmissions on the networked machine.

There are three ways to configure security to enable uploads to a network file share using anonymous authentication:

  1. Create identical local accounts (e.g. IUSR_FileUp) on the Web server and file server. The two accounts must have the same username and password. On the Web server, use this account for anonymous access to your Web site. On the file server, grant this account read, write, and delete privileges to the upload directory.

    To create a new user (Do this on both servers):

    1. Go to Start/Program Files/Administrative Tools/User Manager.
    2. Open the User menu, and select New User.
    3. Enter a username and password for the new user.

    To use the new account for anonymous access to the Web site:

    1. Enter the Microsoft Management Console.
    2. Right click on the Default Web Site and choose Properties.
    3. Choose the Directory Security tab.
    4. Under Anonymous Access and Authentication Control, choose the Edit button.
    5. Uncheck Enable Automatic Password Synchronization.
    6. Browse to select the account, and enter the password.

    To grant the new user access to the shared folder on the file server:

    1. Right-click the shared folder.
    2. Open Properties.
    3. Select the Security tab.
    4. Select Permissions.
    5. In the Directory Permissions dialog box, select Add.
    6. In "Add Users and Groups," display the local server name in the "Display Names From" drop-down list box.
    7. Highlight the desired account in the scroll box, and click Add.
    8. In the Permissions window, select "Modify".

  2. Use domain accounts for anonymous authentication on the Web server and file server:

    1. Follow the directions above to select an account to be used for anonymous authentication on your Web site. When browsing for an account, select a domain account (make sure that the domain name appears in the “List Names From�? drop-down box).
    2. Follow the directions above to grant the new user access to the shared folder on the file server. When browsing for an account, select a domain account (make sure that the domain name appears in the “List Names From�? drop-down box).

  3. Clone the IUSR account on the Web server to a local account on the file server. Download KB18_files1.zip which contains the script iusrpw.vbs. If you run iusrpw.vbs on the Web server, it will output the user name and password for the IUSR account stored in IIS's metabase. You will need to copy these down and create a user on the file server with the same credentials. The new username should match AnonymousUserName and the password should match AnonymousUserPass that were outputted by running iusrpw.vbs on the Web server.

    To create a new user (do this on the file server only):

    1. Go to Start/Program Files/Administrative Tools/User Manager.
    2. Open the User menu, and select New User.
    3. Enter a username (e.g. IUSR_WebServer) and password (obtained from iusrpw.vbs) for the new user.

    To grant the new user access to the shared folder on the file server:

    1. Right-click the shared folder.
    2. Open Properties.
    3. Select the Security tab.
    4. Select Permissions.
    5. In the Directory Permissions dialog box, select Add.
    6. In "Add Users and Groups," display the local server name in the "Display Names From" drop-down list box.
    7. Highlight the desired account in the scroll box, and click Add.
    8. In the Permissions window, select "Modify".

  4. Basic Authentication or Kerberos can also be used for saving to a network share if the authenticated domain account has access to the network file share.


Production Notes

  • High Volume Usage
  • Notes for ISPs


High Volume Usage

SoftArtisans FileUp and Physical Memory Usage

SoftArtisans FileUpis frugal in terms of memory usage. For a given upload, only approximately 64 KB of the file is in memory at any given time. This permits concurrent uploads of very large files without using significant paging resources.

FileUphas performance monitors that let you monitor the usage and server load. See FileUpPerformance Monitor Counters for a list of all the available counters.

If you are using Performance Monitor to examine memory usage in IIS (inetinfo process), you may see large spikes during uploads. This is normal when there is memory available. FileUpwill issue many write requests to the server OS (NT, Windows 2000, XP, Windows 2003). Windows is very efficient about using available memory to reduce physical write requests to disk. It has been our experience that it handles large I/O requests very well.

During these spikes, you may also observe a large number of page faults per second. In this circumstance, paging is a normal occurrence. A distinction must be made between a "hard" page fault where the disk is accessed and a "soft" page fault where a process requests additional memory and it is granted immediately. A soft page fault is the normal mechanism for a process to ask for additional memory.

If you want to observe memory usage by IIS in general, or FileUpin particular, the following metrics are of particular importance:

    • Private bytes - to detect if memory is leaking over time.
    • Pages Input/sec or Pages Output/sec - to detect if physical memory starvation is occurring.

SoftArtisans FileUphas been successfully tested against concurrent uploads of more than 100 MB each and with tens of thousands of uploads per hour on a dual processor NT server machine.

Running "In-Process" and "Out-of-Process"

IIS allows you to define web applications as running in the same address space as the web server ("in-process") or in a separate address space ("out-of-process"). FileUpcan be used in both of these scenarios successfully.

If you anticipate uploads or downloads greater than 256 KB, for performance purposes it would be advisable to keep web applications "in-process". Otherwise, there will be a significant performance penalty when marshalling large quantities of data across process boundaries.


Notes for ISPs

This section will be of particular interest to ISPs and other web site hosts.

Licensing and Sharing SoftArtisans FileUp

SoftArtisans FileUpis licensed on a per-server basis. There are no per-user, per-processor or per-concurrent upload license costs. If the ISP is hosting multiple sites or clients on a single server, every site or client on that server can create an instance of FileUpand start performing uploads.

If a single customer purchases FileUpand wants the ISP to install it on their server, it will automatically be available to all customers on that same server. You can limit usage to only a single customer.

When a customer is interested in FileUp,many ISPs elect to purchase the componenton their behalf. There are several reasons for this:

  • The ISP is directly supported by SoftArtisans, Inc. rather than passing through the intermediary of their customer.
  • The upload and secure download features of FileUpare additional features that can be offered by the ISP to prospective customers.
  • The price is reasonable.

Installation Considerations

An ISP customer cannot install FileUpwithout the assistance of the ISP. Even if your customer transfers the SAFILEUP.DLL to your server, it still requires administrator access to register the DLL in the system registry. (see Installation Instructions).

Disallowing Sharing of SoftArtisans FileUp

As mentioned previously, by default FileUpwill be available to all customers hosted on your web site. In IIS it is possible to finely tune security settings on a per-virtual server or per-site basis.

  • Prevent Access to the FileUp dlls by the default ASP and ASP.NET accounts.Any account wishing to access the FileUp dlls, requires "read" and "read and write" NTFS access permissions. You may choose to explicitly deny these permissions to the local ASPNET (Windows 2000, XP) or NETWORK SERVICE (Windows 2003) user account as well as the ISUR account. Both of which are the default accounts assumed by a web application in ASP or ASP.NET.

  • If the default Anonymous User account (IUSR account) is explicitly denied permissions on the FileUp dlls, but Anonymous Authentication is required for the FileUp application, you will need to change the account used by the FileUp web application for Anonymous Authentication. This is done as follows:
    1. Create a specific NT account with "log on locally" rights.
    2. Using the Microsoft Management Console, set the anonymous user for the chosen site as the the newly created account.
    3. Ensure that the NTFS permissions on FileUp dlls allow access by the newly created account only, and not IUSR_MachineName. This will prevent other users from creating an instance of FileUp.
  • If the default ASPNET(Windows 2000, XP) or NETWORK SERVICE (Windows 2003) user account is explicitly denied permissions on the FileUp dlls, you will want to specify a different account to be used by your FileUp web application. This can be done in the web.config file of your application.

Auditing Your Web Sites

For maximum security, it would be prudent to occasionally audit your customer's code. In particular, you should verify:

  • That the destinations of the uploads are in appropriate directories.
  • That an instance of FileUpis not created as an Application variable. Creating an instance of FileUpas an Application variable is a security risk.

Disabling SoftArtisans FileUp Features

It is possible to disable certain featuresof FileUpvia Registry settings. Of particular importance is the ability to restrict uploads to virtual directories.


Large Uploads in ASP

  • ScriptTimeout
  • Connection Timeout
  • MaxClientRequestBuffer
  • AspMaxRequestEntityAllowed Metabase Property
ScriptTimeout

ASP's ScriptTimeout property sets the length of time in seconds that ASP pages will allow for a script to execute. The default value of this property in IIS is 90 seconds. In a file upload, the ASP page must execute for the duration of the upload. If your user is transferring information over a slow line or is transferring a large quantity of information, it is easy to exceed this limit.

To increase the ASP ScriptTimeout in IIS:

  1. Right-click the application that will perform uploads, and select Properties.
  2. Select the Virtual Directory tab and click Configuration.
  3. Select App Options.
  4. In ASP Script Timeout, enter a value in seconds.

To increase the ASP ScriptTimeout in script, set the property Server.ScriptTimeout. For example:

<% Server.ScriptTimeout = 300 %>

The FileUp registry key DynamicAdjustScriptTimeout allows you to ensure that large uploads will not be timed out. If this key is set to True, IIS's ScriptTimeout value will be increased until an upload is complete.

To enable DynamicAdjustScriptTimeout:

  1. Open the Start menu and select Run...

  2. Enter regedit and click Ok.

  3. Open the folder HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\FileUp\Parameters.

  4. Double click DynamicAdjustScriptTimeout. An Edit DWORD Value dialog will open.

  5. In the Value Data field, enter 1.

Top

ConnectionTimeout

IIS's Connection Timeout property sets a time in seconds at which the server will disconnect an inactive connection. The default value is 900 seconds. To allow very large uploads to complete it may be necessary to increase this value. To reset Connection Timeout:

  1. In IIS, right-click Default Web Site and select Properties.

  2. Select the Web Site tab.

  3. In the Connection Timeout box, enter a new value.

Top

MaxClientRequestBuffer

The IIS parameter MaxClientRequestBuffer sets a maximum size for the first chunk of an HTTP request. The first chunk will usually contain only a request's header fields, which includes all data in a request that is not part of the request's entity body. The default value of MaxClientRequestBuffer is 128 KB.

AspMaxRequestEntityAllowed Metabase Property

In IIS 6.0, Microsoft introduced a new metabase property setting, AspMaxRequestEntityAllowed, to help users secure their web servers more easily. AspMaxRequestEntityAllowed lets users specify the maximum number of bytes allowed in the entity body of an ASP request. Unfortunately, this setting interferes with large FileUpEE uploads with ASP. If this setting is too low, you can observe the temp files being created but never saved, or IIS could return a 403 error response.

Additionally, multiple file uploads may return no error, but instead any file sent after the AspMaxRequestEntityAllowed value is exceeded will not be saved. The temp files will be created in the Path directory for all files in the transfer, but they will not be saved in the destination directory.

Hence, if you are performing large FileUpEE uploads in ASP on a server running IIS 6, you will need to edit the Metabase.xml file for your IIS installation. You can find your Metabase.xml file at C:\Windows\System32\Inetsrv. Find the AspMaxRequestEntityAllowed node and change the setting to a value just large enough for your largest uploads in bytes. For instance, if you expect no uploads greater than 1 GB, you can set the value to 1073741824.

For more information on the AspMaxRequestEntityAllowed metabase property, please read this article at the Microsoft Windows Server 2003 TechCenter: AspMaxRequestLengthEntityAllowed Metabase Property (IIS 6.0)

Top


Configuration and Application Planning for ASP.NET

  • Understanding the Concepts: Client vs. Server
  • Permissions, Caching and Saving
  • Development Notes for ASP.NET
  • Production Notes


Planning for Caching, Saving and Transferring

Planning Permissions for Caching, Saving and Transferring (ASP.NET)

Plan for a Cache Location

FileUp requires a directory to which to cache an upload under the following circumstances:

  • In ASP.NET when the HttpModule is enabled, the HttpModule requires a path for caching.
  • If the HttpModule is not enabled, then the FileUp object requires a location, provided that the UseMemory property is set to "false".

The caching directory does not need to be exposed as a virtual directory. For security reasons, it may be best to purposely avoid caching to a directory that is also exposed as a virtual directory.

Once the directory is choosen, you must provide appropriate NTFS permissions so that FileUp can access this directory. This directory requires "Read", "Write" and "Modify" permissions for the identity assumed by your web application.

To inform the HttpModule or the FileUp object where it should cache, please see the section Default Directory for Cached Files

Under What Identity will the Caching Occur?

In ASP.NET, the identity is determined by the following:

  • If you are using the HttpModule (recommended), it will intercept and cache the upload before the script is run and before the FileUp object is instantiated; therefore COM+ settings and calls to FileManager in script will not change identity in time to affect caching. The identity will be determined by web.config settings. The default identity is the ASPNET user account under Windows 2000 and XP or the NETWORK SERVICE account under Windows 2003 Server. For extensive discussion on how to change identity from the default setting, please see Understanding Permissions: How to Determine or Set Identity .

  • Although it is not recommended, if you disable the HttpModule, you will need to be aware that the identity for caching might be different under certain special circumstances.

    • If FileUp is installed in COM+ as a server package with a specified identity, this is identity will take precedence over the application identity.

    • If the FileUp script changes page-level identity (before caching) by calling FileManager's LogOnUser method, this is the identity that will be used, unless FileUp is installed in COM+ as described above.

Plan for a Save Location

FileUp requires a location to which the uploaded files should be saved. This can be the same directory as was choosen for a caching location, it may be a different directory or directories, or it may be a database.

Once the directory or directories are choosen, you must provide appropriate NTFS permissions so that FileUp can access this directory. To save to a directory, the identity under which FileUp is running requires "Read", "Write" and "Modify" permissions. If you are saving to a file-based database, such as Microsoft Access, you need to provide "Read" and "Write" permissions to this identity for the directory in which the file-based database resides.

Under What Identity will the Saving Occur?

In ASP.NET, the identity is determined as follows:

  • The identity assumed by FileUp is the identity of the web application as set in the application's web.config file. The default identity is the ASPNET user account. The two exceptions to this are described in the following bullet points.
  • If FileUp is installed in COM+ as a server package with a specified identity, this is the identity that takes precedence.

  • If the FileUp script changes page-level identity (before caching) by calling FileManager's LogOnUser method, this is the identity that will be used, unless FileUp is installed in COM+ as described above.

For more information on where to set the save paths in your application, please see the Programmer's Reference for the following property and methods:[FileUp].Path,[FileUp|File].Save,[FileUp|File].SaveAs, [FileUp|File].SaveAsBlob, [FileUp].SaveBinaryAs, [FileUp].SaveRecursiveand [FileUp|File].SaveInVirtual

Downloading with FileUp's TransferFile method

The directories from which FileUp will be transferring files, will require NTFS "read" permission, which is set in the same way as described in "Save Location". Identity is determined likewise.

For more information on where to set the path from which files should be downloaded, please see the Programmer's Reference for the following methods FileUp.TransferFile and FileUp.TransferBlob


Default Directory for Cached Files

When you upload a file to the server, it is cached before you save it.

ASP.NET: The HttpModule Temp Directory

FileUp's interceptor technology, the HttpModule - caches request data before it is processed by ASP.NET. The cache location is set in the Windows registry. By default, the cache location is the system's default directory for cached files, which is determined by the system environment variable TEMP. To set a different temp directory for the HttpModule:

  1. Open the Start menu, and select Run.
  2. Enter regedit and click Ok.
  3. Open HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\SA-FileUp\Parameters.
  4. Right-click FileUpTempDir and select Modify.
  5. In Value Data, enter the path and folder name.

Adequate NTFS permissions must be set on the cache directory. The HttpModule functions as whatever identity is set for your application in your web.config file. The default identity is the local ASPNET user account. The account identity assumed by the HttpModule requires "read", "write" and "modify" permissions on the cache directory.

For the FileUp Object (ASP.NET when the HttpModule is not used)

Although it is not recommended, if you are using FileUP in ASP.NET withoutthe HttpModule, please see Default Directory for Cached Files for ASP.


Understanding Permissions

Understanding Permissions for FileUp
on the Web Server (ASP.NET)

Setting permissions for your FileUp .NET web application involves only three basic steps:

  1. Determine Caching and Saving locations.
  2. Determine Identity.
  3. Set NTFS "Read", "Write" and "Modify" permissions on your caching and saving locations for the appropriate identity.
These three steps often prove to be the first stumbling blocks for new users of FileUp. Because webserver security is highly configurable, there are many possible variations of each of the above steps. You will need to understand these variations in order to troubleshoot permissions errors, should they be encountered. Topics covered in this chapter include:

  • Understanding How FileUp Works in Relation to the File System
  • Caching: When and Where
  • Saving: When and Where
  • Determing Identity
  • Setting NTFS permissions

In the process of uploading a file with FileUp, your web application will be performing some basic file system tasks such as caching, saving and renaming that require you to understand NTFS permissions.

Understanding How FileUp Works in Relation to the File System

When an upload request is received on the server, FileUp has two responsibilities that may require interaction with the server's file system:

  • Caching the request to either the file system or to memory, so that it can parsed for form elements and files.
  • Providing a final destination for the files, either to the file system or to a database

In order to parse through an upload request, FileUp must be able to cache the request, either to disk or memory. Caching the upload request to disk requires "Read", "Write" and "Modify" NTFS permissions on the caching directory. Later, when FileUp is instructed to save the file, these same permissions are required on the directory to which the files will be saved.

When and where does the upload get cached?

This happens at different points and in different ways depending on whether or not you are using FileUp’s HttpModule.

In ASP.NET you have the choice to plan your application to use FileUp's HttpModule, or to upload without the module. For the sake of server performance, it is recommended that you use the HttpModule.

ASP.NET caches the upload request to memory before FileUp can take action on it. This means that you may quickly exhaust your server's memory resources if you are uploading either large or many concurrent files. The HttpModule can be used to intercept the upload request before ASP.NET processes it. The HttpModule will cache the upload request to disk and strip the files from the Request. The Request will then still passed along to ASP.NET, but the request is now free of the files. ASP.NET will now cache a very small request to memory, instead of a request laden with file content.

Caching when the HttpModule is used:

Since the HttpModule intercepts the upload request before the ASP.NET script is executed, you will not be setting the caching location in script. Instead, the cache directory can be set in the FileUpTempDir registry setting. To check or set this value:

  1. Open the Start menu, and select Run.
  2. Enter regedit and click Ok.
  3. Open HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\SA-FileUp\Parameters.
  4. Right-click FileUpTempDir and select Modify.
  5. In Value Data, enter the path and folder name.

Caching when the HttpModule is not used:

If the HttpModule is not employed, ASP.NET will handle caching like it would be done in ASP. It will read the upload request into memory, but in order for FileUp to get a handle on the files, it will still need to cache the upload request either to disk or to memory. Because the HttpModule did not do this already, FileUp will cache the upload request as soon as any element of the upload request, such as a file or a form element, is called in the script. At that point, FileUp will check to see if its Path property has been populated. If it has, it will cache the upload request to this directory. Setting the path property before referencing any files or form elements is considered "best practice"; however, if the Pathproperty has not yet been set to a valid path, FileUp will check the web server’s system TEMP variable and attempt to cache the upload request there.

The exception to this case is when the UseMemory property of FileUp is set to "true". If UseMemory is set to "true", FileUp will not cache to disk, but will instead cache to memory. Caching to memory requires neither a directory nor NTFS permissions. You will still however, need to understand how to set NTFS permissions on the directory to which the upload is finally saved, if you call “Save�? or “SaveAs�? on an uploaded file.

In the following code sample, you can see that following best practice, on Line 9, the Path property is set immediately after instantiating FileUp. By setting this property immediately after instantiating FileUp, you can be assured that FileUp will cache to the directory specified in the Path property. FileUp is forced to cache the upload when the first form element is accessed, at line 11, and because the path property has been set already, FileUp will cache to “C:\MyCachingDirectory�?.

Line 1: | '--- Declarations
Line 2: | Dim oFileUp
Line 3: | '--- Instantiate the FileUp object
Line 4: | Set oFileUp = Server.CreateObject("SoftArtisans.FileUp")
Line 5: | '--- Set the Path property to the location you wish to
Line 6: | '--- temporarily cache the incoming file before saving
Line 7: | '--- Note: This property should be set immediately after
Line 8: | '--- instantiating the FileUp object
Line 9: | oFileUp.Path = “C:\MyCachingDirectory�?
Line10: | '--- Confirm that the control “myFile1�? is a file input control
Line11: | If IsObject(oFileUp.Form("myFile1")) Then

When and where does the upload get saved?

The uploaded files do not get saved to their final destination until one of the "Save" methods are called (Save, SaveAs, SaveAsBlob, SaveRecursive).

The following table will show you where to set permissions for saving, based on the method chosen.

Method | Where to set permissions
Save | The Save method looks for a directory to be provided in the Path property. If no directory is provided, then the directory specified in the System Temp variable will be used.
SaveAs

If only a filename has been provided as the argument for the SaveAs method, then FileUp will check the Path property as described in the Save method.

If a complete path has been provided as the argument for the SaveAs method, set permissions on this directory.

SaveAsBlob | If uploading to a file-based database, such as Microsoft Access, be certain to set access permissions on the directory in which the database is located, or on the database file itself.
SaveRecursive | SaveRecursive is dependent on the Path property in the same manner as is described for the Save method.

Under what identity does FileUp run? To whom are the NTFS permissions granted?

NTFS permissions need to be granted to users or groups. You will therefore need to understand what identity FileUp assumes.

The default behavior of any object running in a web page is to assume the identity of the web application. Because you must be certain of the identity of FileUp in order to correctly set NTFS permissions, some less commonly used means of changing the identity of FileUp have been listed as well.

  1. FileUp executes under the same identity as your web application.
    This is the most common scenario. FileUp will assume the identity that is set for your web application in the web.config file. The default identity is the ASPNET user account under Windows 2000 and XP or the NETWORK SERVICE account under Windows 2003 Server."

  2. SoftArtisans FileManager can be used to change identity of FileUp within the ASP.NET code in a LogOnUser/RevertToSelf block.
    If caching or saving occurs within this block, FileUp will assume the identity specified in the LogOnUser method.

  3. COM+ can be used to specify the identity of the FileUp dll. If FileUp is installed in COM+ as a server package with a specified identity, this identity will be used. This takes priority over any web application settings or the use of FileManager's LogOnUser method.

How to Determine or Set Identity
  1. Check the web.config settings.Have you enabled impersonation?

    No

    By default, impersonation is not enabled and the web application will run as the ASPNET or NETWORK SERVICE account. If impersonation is enabled, it will be done in the "identity" node of the web.config file:

    <system.web>
    ...
    <identity impersonate="true" />
    ...
    </system.web>

    Yes

    If impersonation is enabled, is there an account specified in the user attribute of the identity node?

    • Yes. The web application will assume the identity of the user specified in the username attribute of the identity node.
    • No. The web application will assume the identity of the authenticated user in IIS. The default user is the IUSR account for anonymous access. You will need to check identity of the web application as specified in IIS.

      Check the Identity of the Authenticated User in IIS.

      1. Locate your web application in IIS.
      2. Right-click on the application directory, choose "properties".
      3. Select the "Directory Security" tab.
      4. In the section "Anonymous access and authentication control", click on the "edit" button. This tab lets you know what your current settings are for your application.

      • Anonymous Access
        If this box is checked, it means that all users will have anonymous access to your web application. This means that there is no authentication required and your web application will run as the user specified in the User Name text box.

        This dialog shows the username and password of the account used by your web application when anonymous access is granted. The default account is the IUSR account, "IUSR_[machine_name]" and the password is controlled by IIS. The IUSR account is a local account and a member of the group "guests". This account can be changed, but this has implications outside the scope of this tutorial. If you do decide to change this account, consult the documentation for IIS to determine what other actions need to be taken (for example, granting the right to “Log on locally�? to the new user account).

        Assuming that you do not change this account, the IUSR account is the account to which you must grant the appropriate NTFS permissions when FileUp is assuming the identity of your web application.

      • Basic Authentication or Digest Authentication
        If this box is checked, the user is prompted for a username and password when they access the site. If the username and password match an account recognized by the web server, then the user is granted access and the web application runs as that user's identity. In this situation that particular user, or a group to which this user belongs, must be given the "read", "write" and "modify" permissions on the directory to which FileUp will cache or save.

      • Integrated Windows Authentication
        Checking this box assumes that the client will be on the same windows domain as the web server, which may be the case for an intranet application. The browser will pass the NT login credentials from the client machine to the web server for authentication. The web application will then run as this domain user. Integrated Windows Authentication only allows you to cache or save files to the web server. You will not be able to pass on the NT login credentials to another server, which is the case when you attempt to cache or save files to a network share. (For more information on saving files to a network share, please see Uploading to a Network Share .)

  • Change the identity of FileUp by using FileManager.

    FileManager is distributed with FileUp. By calling FileManager’s LogOnUserand RevertToSelf method, you can change FileUp’s identity within the ASP or ASP.NET script, without changing the identity of the web application in IIS. To be certain of FileUp’s identity, you should check your code for calls to FileManager’s LogOnUser/RevertToSelf methods. For more information on using LogOnUser/RevertToSelf, please see the FileManager Programmer's Reference

    Confirm identity by using FileManager.

    With any of these web application or page level means of setting identity (in IIS, in script with FileManager), you can confirm your understanding of the identity assumed by your web application by using SoftArtisans FileManager to report the identity with the CurrentUser property. For more information on the CurrentUserproperty and a code snippet, please see the FileManagerh Programmer's Reference.

  • Set or check FileUp's identity at the dll level in a COM+ server package installation.

    You can force an identity change at the dll level by installing FileUp in COM+ as a server package that runs as a specific user. When the FileUp web application runs, it will run as the identity specified in IIS, but FileUp itself will run as the user specified in COM+. Because the identity is changing in the COM+ layer and not in the web application layer, tools such as FileManager’s CurrentUser property, will not be able to report this identity switch. When troubleshooting identity problems, you will want to open the COM+ manager to see if FileUp’s has been configured to run in a COM+ server package under a specific account. To check this:

    1. Open the control panel
    2. Open “Administrative Tools�?
    3. Open “Component Services�?
    4. In Component Services, navigate to the “computers�? folder.
    5. Under the “computers folder�?, navigate to the “COM+�? folder
    6. Under the COM+ folder look for a package named “SA-FileUp�?.
    7. If the “SA-FileUp�? package exists, FileUp has been installed in COM+. Next, check to see if it is installed as a server or library package.
    8. Right-click on the package and choose “properties�?.
    9. In the properties dialog, choose the “Activation�? tab. The Activation type will be either “library�? or “server�?.
    10. If FileUp is installed as “library�? package, FileUp will assume the identity of the web application when it is run. If FileUp is installed as a server package, it is possible to specify a different identity for FileUp, regardless of web application settings. To check for a specified identity, select the “Identity�? tab.
    11. If an identity is specified, you will need to grant NTFS permissions on your caching and saving directories for this identity, even if the web application is set to a different identity.
    12. If the package is set to run as the “current logged on user�? then FileUp will continue to run as the identity specified for the web application in IIS.

Setting NTFS Permissions

Once both the identity of FileUp and the caching/saving locations have been determined, NTFS permissions can be set.

  1. Open Windows Explorer and navigate to the directories to which you will be instructing FileUp to cache or save.
  2. Right click on the directory, choose “properties�?.
  3. From the properties dialog, choose the “security�? tab.
  4. On the security tab, you will see a list of users. Check to see if the identity FileUp will be running as, is listed here.
  5. If the user is not listed, you will need to add the user, by clicking the “add�? button.
  6. In the dialog to select users or groups, select the user that FileUp will be running as. For example, if you are using the default ASP.NET settings and therefore letting your application run as the local ASPNET (Windows 2000 and XP) or NETWORK SYSTEM (Windows 2003) account, select the local machine domain to obtain a list of local users, then select the user named "ASPNET" or "NETWORK SERVICE. Click "OK" to return to the “security�? dialog.
  7. Select the user that you just added to the security list. With this user selected, now set the following permissions: “Allow�? on “Read�?, “Write�? and “Modify�?.

  8. If the permissions cannot be changed, check to see if the “Allow inheritable permissions�? check box is selected. If it is, you will need to uncheck it in order to be able to change the permissions on this directory. You will want to make a note of the inherited permissions, as removing them may affect other applications. You will be prompted to either completely remove the inherited permissions or to copy the existing permissions. If you are uncertain of which action to take, copy the existing permissions and then add your FileUp user permissions in addition to your existing permissions.
  9. Click OK to apply and save your changes. Repeat this process for each directory to which FileUp requires access due to caching or saving activity.

Summary for setting appropriate permissions for FileUp in ASP.NET

  1. Determine Caching and Saving locations.
  2. Determine Identity.
  3. Set NTFS "Read", "Write" and "Modify" permissions on your caching and saving locations for the appropriate identity..


Special Permissions: Uploading to a Network Share

Uploading to a Network Share

FileUp supports uploading to a network share, provided that the path is accessible to the user account under which your application is running.

When saving to a network share, there are a number of issues to be aware of with regard to the identity of your upload application (or the upload processing page). First of all, if your application or page is running under a local account such as the default anonymous acount (IUSR_MachineName) the upload will fail because this account does not have network priviledges. Windows Integrated Authentication is also not an option because IIS will not pass the credentials to the networked server. Therefore, one of the following approaches must be used.

UNC Paths vs. Mapped Drives

Mapped drives are dependent on user profiles. If you intend to use a mapped drive in your FileUp script, you must be certain that the mapped drive is available to the user account under which your application is running. A UNC style path is not dependent on user profiles and is a better solution when application identity varies.

Using an account that has NTFS persmissions on the networked machine.

There are three ways to configure security to enable uploads to a network file share using anonymous authentication:

  1. Create identical local accounts (e.g. IUSR_FileUp) on the Web server and file server. Specify this account in the web.config of your ASP.NET application, or if impersonation is enabled, follow the steps below for setting up this account in the IIS console. The two accounts must have the same username and password. On the Web server, use this account for anonymous access to your Web site. On the file server, grant this account read, write, and delete privileges to the upload directory.

    To create a new user (Do this on both servers):

    1. Go to Start/Program Files/Administrative Tools/User Manager.
    2. Open the User menu, and select New User.
    3. Enter a username and password for the new user.

    To use the new account for anonymous access to the Web site:

    1. Enter the Microsoft Management Console.
    2. Right click on the Default Web Site and choose Properties.
    3. Choose the Directory Security tab.
    4. Under Anonymous Access and Authentication Control, choose the Edit button.
    5. Uncheck Enable Automatic Password Synchronization.
    6. Browse to select the account, and enter the password.

    To grant the new user access to the shared folder on the file server:

    1. Right-click the shared folder.
    2. Open Properties.
    3. Select the Security tab.
    4. Select Permissions.
    5. In the Directory Permissions dialog box, select Add.
    6. In "Add Users and Groups," display the local server name in the "Display Names From" drop-down list box.
    7. Highlight the desired account in the scroll box, and click Add.
    8. In the Permissions window, select "Modify".

  2. Use domain accounts for anonymous authentication on the Web server and file server. Specify this account in the web.config file or your application, or if you have enabled impersonation, set up this account in IIS by following these instructions:

    1. Follow the directions above to select an account to be used for anonymous authentication on your Web site. When browsing for an account, select a domain account (make sure that the domain name appears in the “List Names From�? drop-down box).
    2. Follow the directions above to grant the new user access to the shared folder on the file server. When browsing for an account, select a domain account (make sure that the domain name appears in the “List Names From�? drop-down box).

  3. Clone the IUSR account. If your application is running under the IUSR_<machinename> account because you have impersonation turned on in the web.config, you can make an identical local account on the fileserver. Download KB18_files1.zip which contains the script iusrpw.vbs. If you run iusrpw.vbs on the Web server, it will output the user name and password for the IUSR account stored in IIS's metabase. You will need to copy these down and create a user on the file server with the same credentials. The new username should match AnonymousUserName and the password should match AnonymousUserPass that were outputted by running iusrpw.vbs on the Web server.

    To create a new user (do this on the file server only):

    1. Go to Start/Program Files/Administrative Tools/User Manager.
    2. Open the User menu, and select New User.
    3. Enter a username (e.g. IUSR_WebServer) and password (obtained from iusrpw.vbs) for the new user.

    To grant the new user access to the shared folder on the file server:

    1. Right-click the shared folder.
    2. Open Properties.
    3. Select the Security tab.
    4. Select Permissions.
    5. In the Directory Permissions dialog box, select Add.
    6. In "Add Users and Groups," display the local server name in the "Display Names From" drop-down list box.
    7. Highlight the desired account in the scroll box, and click Add.
    8. In the Permissions window, select "Modify".

  4. Basic Authentication or Kerberos can also be used for saving to a network share if the authenticated domain account has access to the network file share.


Development Notes for ASP.NET

  • Using the .uplx Extension in .NET
  • Notes on Debugging
  • Scripting in C#
  • Properly Disposing of Resources in .NET


Using the .uplx Extension in .NET

Posting to files with a .uplx extension invokes FileUp's HttpModule. The HttpModule is necessary to provide accurate progress indication and adequate memory management when uploading with ASP.NET. In a production environment, any page receiving an upload should be named with a .uplx extension to take advantage of the HttpModule. Although .uplx pages are just ASP.NET Web forms with a different file extension, you may find that Visual Studio .NET does not handle .uplx files in the same way that it does .aspx files. Visual Studio .NET may not allow you to edit .uplx Web forms in the Web form designer, or recognize the code-behind relationship between the Web form and the class file. This section explains how to use the .uplx extension when developing a FileUp application in Visual Studio .NET.

Why use the .uplx file extension?
  • To utilize FileUp's accurate server-side progress indication for uploads.
  • To bypass ASP.NET's poor memory management during processing of upload requests.
            •
    Why use the .aspx extension for development?
  • To use Visual Studio .NET's advanced developer features like colorized code, IntelliSense, and drag-and-drop controls.
  • To use Visual Studio .NET's Web form and code-behind pairing
            •
    Do I need to change the file extensions to get my samples to run?
    No. The pages will run in Visual Studio .NET whether they are .uplx or .aspx, as long as the file extension is mapped to aspnet_isapi.dll. What you lose when opening .uplx pages in Visual Studio .NET are the advanced editingfeatures.

    To configure FileUp sample code to integrate with Visual Studio .NET:

    1. Change the sample application's file extensions from .uplx to .aspx. For example:

      FileAndForm.uplx -> FileAndForm.aspx
      FileAndForm.uplx.cs -> FileAndForm.aspx.cs

    2. Import Sample Files:

      1. Open Visual Studio .NET to create a new project.
      2. Specify either VB.NET or C# and name the Web project.
      3. Right-click the project name in the Visual Studio .NET Solution Explorer.
      4. Choose Add, then Add Existing Item.
      5. Browse to and add the FileUp sample Web form and code-behind pages that you renamed with the .aspx extension.

    3. At the top of the Web form page, rename the Src directive to CodeBehind. For example, change: <%@ Page Language="c#" Inherits="FileUpSESamples.Simple"
      Debug="True" Src="Simple.uplx.cs" AutoEventWireup="false" %>

      To:

      <%@ Page Language="c#" Inherits="FileUpSESamples.Simple"
      Debug="True" CodeBehind="Simple.aspx.cs" AutoEventWireup="false" %>
    4. Add Object References:

      1. Right-click References in the Visual Studio .NET Solution Explorer.
      2. Choose Add References.
      3. Click Browse, go to the folder SoftArtisans\FileUp\DotNet, and select FileUp.dll, SAPrgres.dll, and - for use when the extension is .uplx - FileUpModule.dll. Finally, click Ok. Note: If you registered the dll files manually with regsvr32, and have more than one copy of each file, make sure you select the files you registered; for more information, see Installing FileUp for ASP.NET.

    5. Open the application's web.config file and add the following node: <httpModules>
      <add name="FileUpModule" type="SoftArtisans.Net.FileUpModule,
      FileUpModule, Version=$fu.version.module.build$,
      Culture=neutral, PublicKeyToken=f593502af6ee46ae"> </httpModules>
      Note: The version attribute in web.config must match the FileUpModule.dll version exactly. To determine the dll version, locate FileUpModule.dll in Windows Explorer, right-click the file, choose Properties, select the Version tab. The file version is listed at the top.

    To revert FileUp files for production:

    1. For the Web form that posts to the code-behind page, change the file extension from .aspx to .uplx. For example:

      FileAndForm.aspx -> FileAndForm.uplx

    2. Be certain that the FileUpModule.dll has been added to either the GAC or the application's bin directory. (see: Making FileUp available to .NET applications )

    3. Confirm that the HttpModule node has been added to either the web.config or machine.config depending on your configuration. (see: Making FileUp available to .NET applications )

    Which files should I convert from .aspx to .uplx?
    For production, rename the Web form with a .uplx extension. You do not have to rename the code-behind page that the Web form posts to. The progress indicator page should have a .aspx extension; while it is involved in an upload, it does not actually process the upload, so it does not need to be changed to uplx.

    Top


Notes on Debugging

Tracing in .NET and the HttpModule

FileUp's HttpModule is compatible with page level tracing, but it is not compatible with application level tracing. The following explains how to enable page level tracing and how to disable application level tracing.

Enable Page Level Tracing

Page-level tracing is compatible with the HttpModule. For debugging during development, you can turn on tracing in the Page directive at the top of your aspx or .uplx pages:

<%@Page trace="true" ... %>

Disable Application Level Tracing

FileUp's HttpModule is incompatible with application-level tracing. If you are using the HttpModule, you must either remove the trace element from your web.config, or set the enabled attribute to "false".

The trace parameters are located within the system.web node of the web.config:

<system.web>
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"/>
</system.web>

If you need to enable application level tracing in ASP.NET, you mustdisable the HttpModule. Enabling tracing in ASP.NET causes the HttpModule to fail to receive and process the Request.

Confirming that the HttpModule is Configured and Working Properly

If the module is configured and working properly in your application, the shape of the request will be changed by the time it is handled by the asp.net dll. To look at the request, save the request out to a file on your server. Add this code to the top of your script, before FileUp handles it. You cannot run both this code and your FileUp code, so just use this as a diagnostic tool.

VB.NET

Request.SaveAs("C:\SaveLocation\MyRequestSaved.txt", True)
Response.End()

C#

Request.SaveAs(@"C:\SaveLocation\MyRequestSaved.txt", true);
Response.End();

If you are not using the httpModule, or if the httpModule is not configured properly, but also not providing an error message for your configuration problem, the request saved out in "MyRequestSaved.txt" will look like this:
POST /SAFileUpSamples/UploadSamples/Simple/ASPNET/VB/Simple.aspx HTTP/1.1
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 669
Content-Type: multipart/form-data; boundary=---------------------------7d53451537c0414
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash,
application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-us
Host: localhost
Referer: http://localhost/SAFileUpSamples/UploadSamples/Simple/ASPNET/VB/Simple.aspx
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 1.0.3705; InfoPath.1)

-----------------------------7d53451537c0414
Content-Disposition: form-data; name="__EVENTTARGET"

UploadBtn
-----------------------------7d53451537c0414
Content-Disposition: form-data; name="__EVENTARGUMENT"

-----------------------------7d53451537c0414
Content-Disposition: form-data; name="__VIEWSTATE"

dDwxOTMwMTM1NzI0Ozs+iFRoqq9pjkE5NrzWZ0hOLyg7Bm0=
-----------------------------7d53451537c0414
Content-Disposition: form-data; name="myFile"; filename="C:\SimpleTextFile.txt"
Content-Type: text/plain

This is the content a simple text file.
This is the end of the content of my simple text file.
-----------------------------7d53451537c0414--

If the httpModule is enabled and configured properly, the request saved out in "MyRequestSaved.txt" will look like this:
POST /SAFileUpSamples/UploadSamples/Simple/ASPNET/VB/Simple.uplx HTTP/1.1
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 600
Content-Type: multipart/form-data; boundary=---------------------------7d53c32537c0414
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword, */* Accept-Encoding: gzip, deflate
Accept-Language: en-us
Host: localhost
Referer: http://localhost/SAFileUpSamples/UploadSamples/Simple/ASPNET/VB/Simple.uplx
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 1.0.3705; InfoPath.1)
X-UploadComplete: 1
X-SaFilterOn: 1

-----------------------------7d53c32537c0414
Content-Disposition: form-data; name="__EVENTTARGET"

UploadBtn
-----------------------------7d53c32537c0414
Content-Disposition: form-data; name="__EVENTARGUMENT"

-----------------------------7d53c32537c0414
Content-Disposition: form-data; name="__VIEWSTATE"

dDwxOTMwMTM1NzI0Ozs+b0ZIvydUb//5LIrL1E6Fi2UHPf0=
-----------------------------7d53c32537c0414
Content-Disposition: form-data; name="myFile"; filename="C:\SimpleTextFile.txt"
Content-Type: text/plain

C:\WINDOWS\TEMP\sa199F.tmp
-----------------------------7d53c32537c0414--

The primary difference between the two requests represents the work of the HttpModule. The Module strips the files from the request and instead provides a pointer to where the file was cached to disk. (In this case, C:\WINDOWS\TEMP\sa199F.tmp)

In addition, the HttpModule will add two headers to the request: X-UploadComplete and X-SaFilterOn. Both values will be "1".


Note for C# Developers

Casting

C# is a strongly typed language. Therefore, when you use FileUp in C#, you must cast FileUp's objects to the appropriate type, as follows.

Object | FileUp.Form (form element)
Type | SaFile
Example | ((SaFile)fileUpload.Form[0]).SaveAs("C:\\file.ext");

Object | FileUp.FormEx member (element of a form collection)
Type | SaMultiSelectCollection
Example | ((SaMultiSelectCollection)fileUpload.FormEx[obj]).Count;


Properly Disposing of Resources in .NET

FileUp is a COM component that provides .NET support. It is not a pure .NET assembly. As such, it contains both "managed" and "unmanaged" code. When using components of this nature on the .NET framework, you must explicitly dispose of the object in order to free up resources used by that object.

This is best done by declaring the FileUp object before a Try...Catch...Finallyblock, instantiating FileUp within the Try block and disposing of FileUp within the Finally block.

C# using SoftArtisans.Net;

...(namespace, class, and other declaration code, )....

private void ProcessUpload()
{
//--- Declare the FileUp object
FileUp fileUpload = null;

try
{
fileUpload = new FileUp(Context);

...(upload processing code)

     }
catch (Exception ex)
{

...(error handling code here)

     }
finally
{
//--- Always call Dispose in the finally block
if (fileUpload != null)
fileUpload.Dispose();
fileUpload = null;
}
}
VB.NET Imports SoftArtisans.Net

...(namespace, class, and other declaration code, )....

Private Sub ProcessUpload()
'--- Declare the FileUp object
Dim fileUpload As FileUp

Try
fileUpload = New FileUp(Context)

...(upload processing code)

     Catch ex As System.Exception

...(error handling code here)

     Finally
'--- Always call FileUp.Dispose in the finally block
If Not (fileUpload Is Nothing) Then
fileUpload.Dispose()
End If
fileUpload = Nothing
End Try
End Sub

(...)


Production Notes

  • Large Uploads in ASP.NET
  • High Volume Usage
  • Notes for ISPs


Large Uploads in ASP.NET

  • FileUp's HttpModule
  • Connection Timeout
  • MaxClientRequestBuffer
  • .NET Settings
ASP.NET Samples
FileUp includes many sample ASP.NET applications in both C# and VB.NET. To run the samples, open a browser window and enter the URL http://localhost/SAFileUpSamples. The sample code is in the folder FileUp\Samples.
The HttpModule

FileUp's HttpModule intercepts selected requests to overcome ASP.NET's inefficient memory utilization and to allow accurate progress indication. The HttpModule intercepts an upload request, reads all the data, and writes it to a temp file chunk by chunk, before forwarding the request to ASP.NET.

For performance reasons, the HttpModule will not intercept all ASP.NET requests. It will intercept ASP.NET requests for files with the extension .uplx. Files with the extension .aspx will not be processed by the filter, and will be sent directly to ASP.NET. This prevents burdening the server with unnecessary use of the HttpModule. So, to use the HttpModule, name your ASP.NET scripts FileName.uplx.

FileUp's automatic installation package will install the HttpModule for FileUp's samples, and create the script mappings for the .uplx extension. See Installing the HttpModule for instructions on installing the HttpModule at the application level or in the Global Assembly Cache.

Upload Size on the Client
While FileUp can process uploads of up to 4-GB, most browsers support uploads of up to 2-GB. Larger uploads must be generated by a client-side control that can handle very large transfers, such as SoftArtisans XFile [image].
Progress Indication in ASP.NET
Under ASP.NET, FileUp's progress indicator is handled by the HttpModule. Therefore, to display accurate progress indication in ASP.NET, upload to a file with the .uplx extension.

Top

ConnectionTimeout

IIS's Connection Timeout property sets a time in seconds at which the server will disconnect an inactive connection. The default value is 900 seconds. To allow very large uploads to complete it may be necessary to increase this value. To reset Connection Timeout:

  1. In IIS, right-click Default Web Site and select Properties.

  2. Select the Web Site tab.

  3. In the Connection Timeout box, enter a new value.

Top

.NET Settings

In the .NET configuration file for your Web application - web.config or machine.config- there are several attributes that can affect the performance of large uploads. To set these attributes at the machine level, modify machine.config (located in [windows directory]\Microsoft.NET\Framework\[.NET Version Directory]\CONFIG). To set the attributes at the application level, modify your application's web.config file.

You will find the following values in the httpRuntime node of machine.config:

  • executionTimeout
    Time in seconds before a request is timed out.

  • maxRequestLength
    Maximum request size in kilobytes that ASP.NET will accept.

  • appRequestQueueLimit
    Maximum number of requests queued for an ASP.NET application. The default value of appRequestQueueLimit is 100. If your server will be handling more than 100 concurrent requests, increase the value of appRequestQueueLimit.

The following attributes are in the processModel node of machine.config:

  • responseDeadlockInterval
    Specifies the time interval, in the format HH:MM:SS, after which the process will be restarted if the following conditions are met:
    • There are queued requests.
    • There has not been a response during this interval.
    The default value of responseDeadlockInterval is 3 minutes. To allow very large uploads, you may have to increase this value. This property must be set in machine.config, not at the application level in web.config. It will affect any response deadlock in ASP.NET and should be used with caution.

  • responseRestartDeadlockInterval

    • Specifies the time, in the format HH:MM:SS, that must elapse after the last restart to cure a deadlock before the process is restarted to cure a deadlock again. This prevents thrashing on processes that require a relatively long startup time. The default value of responseRestartDeadlockInterval is 9 minutes. To allow very large uploads, you may have to increase this value. This property must be set in machine.config, not at the application level in web.config. It will affect any response deadlock in ASP.NET and should be used with caution.

  • maxIoThreads

    • Maximum number of IO threads per CPU in the thread pool. The default value of maxIoThreads is 25. Increasing this value will increase the number of concurrent executing requests, significantly reducing the amount of time it takes to process concurrent requests. This value is particularly important for large uploads using the HttpModule. If you expect many concurrent uploads to your site, you should set maxIoThreads to the number of concurrent uploads that you wish to support.

Top


Making FileUp Available to .NET Applications

  • A Simple Upload in ASP
  • A Simple Upload in ASP.NET
  • Secure Downloading in ASP
  • Secure Downloading in ASP.NET


A Simple Upload in ASP

To allow file uploads, NTFS permissions must be set appropriately for FileUp's temporary and destination directories. The IUSR_MACHINENAME or authenticated user account must have Read, Write, and Modify access to this folder. For more information, see Setting Appropriate Security.

Here is a simple HTML form that uploads a file:

The Client Code
<html>

<head>
<title>Please Upload Your File</title>
</head>

<body>

<form enctype="multipart/form-data" method="post"
action="formresp.asp">

Enter filename to upload:
<input type="file" id="myFile" name="myFile" /><br />
<input type="submit" />

</form>
</body>
</html>

When using an HTML form to upload files, the form submitting the file must contain:

  • The <form> tag attribute enctype="multipart/form-data".

  • An <input type="file" /> tag, including a name attribute.

The form uploads the file to formresp.asp (specified by the <form>tag's action attribute). Formresp.asp contains the following code:

The Server Code
<%@ language="vbscript" %>
<html>

<head>
<title>Upload File Results</title>
</head>

<body>
<%
Dim fileUpload
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

fileUpload.Path = "C:\Temp"

'--- Check to be sure there was a file selected in the form
'--- If so, continue processing
If IsObject(fileUpload.Form("myFile")) Then
If Not fileUpload.Form("myFile").IsEmpty Then

<fileUpload.SaveAs "C:\uploads\upload.out"

Response.Write "FileUp Saved the File Successfully."
Else
Response.Write "There was no file submitted in the form field."
End If
Else
Response.Write "The referenced field does not exist " & _
"or is not of type=""file"""
End If

'--- Dereference FileUp
Set fileUpload = Nothing
%>
</body>
</html>

The following lines process the upload request, and save the uploaded file

  • Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")
    Creates an instance of the FileUpobject.

  • fileUpload.Path= "C:\temp"
    Sets a temporary directory for the upload on the Web server. Always set the path property immediately after creating an instance of FileUp

  • fileUpload.SaveAs"C:\uploads\upload.out"
    Saves the uploaded file on the Web server as "C:\temp\upload.out".

Setting the Path Property

The Path propery must be set before referencing any variables on the form. As soon as a form element is referenced, FileUp will read in the entire contents of the HTTP post, including all form elements and files. Therefore, if you set Path after referencing a form element, by the time the Pathproperty is set, all of the Form data will have been read, and the cache files created, rendering the Path assignment meaningless.

If you do not set the Path property, FileUp will cache the upload in the server's default directory for cached files.

Summary

  • To upload files, there must be two elements on the form:

    • The <form> tag attribute enctype="multipart/form-data".

    • An <input type="file"> tag, including a name attribute.

  • To process the form:

    1. Create an instance of the FileUpobject.
    2. Set the Pathproperty.
    3. Invoke the SaveAsmethod and specify a filename.

Top


A Simple Upload in ASP.NET

FileUp includes many sample ASP.NET applications in both C# and VB.NET. To run the samples, open a browser window and enter the URL http://localhost/SAFileUpSamples. The sample code is in the folder FileUp\Samples.
Overview of setting up a FileUp web application.
  1. Confirm registration of the appropriate dlls, and set the necessary registry keys.
  2. Set up your .NET application for FileUp.
  3. Determine your application identity.
  4. Choose where you want to cache and set up appropriate permissions.
  5. Choose where you want to save and set up appropriate permissions.
  6. Write your code.

The above steps will be demonstrated using the FileUp samples application. Specifically, this tutorial is based on the sample located at: http://[Name of WebServer]/SAFileUpSamples/UploadSamples/Simple/ASPNET. You can follow these instructions and set up your own sample, or you can run the FileUp installer package and choose to install the samples so that all of the necessary pieces (code, directories, web.config file, global.asax file) are in place for you.

Step 1: Confirm registration of the appropriate dlls, and set the necessary registry keys.

FileUp provides .NET support through a built-in interop assembly, but it is still a COM component. In order to use FileUp in a .NET application, you must first start by confirming that the appropriate dlls have been registered. For more detailed instructions on installation and dll registration, please see the step-by-step instructions in the Installation Chapter, Installing FileUp for ASP and ASP.NET.

In order to use FileUp in ASP.NET with the HttpModule, you must populate the FileUpTempDirregistry key. This key will provide the HttpModule with a caching location. This and other keys are available and listed at Tailoring Your Installation: FileUp Registry Keys.

Step 2: Set up your .NET application for FileUp.

At this step, the decision is made to set up FileUp in the .NET framework for global use or application level use. Since this tutorial is modeled on the FileUp samples, it will demonstrate application level use of FileUp.

2.1 Make the FileUp dlls available to your .NET application
For JIT compilation:(development outside of Visual Studio .NET) From the FileUP\dotnet directory, copy the SAFileup.dll, the SAPrgres.dll and the FileUpModule.dll files to the bin directory
For a Visual Studio .NET project Add the SAFileup.dll, the SAPrgres.dll and the FileUpModule.dll files as references in your project. From the Visual Studio .NET menu,
  1. Choose "Project", then "Add Reference".
  2. From the "Add Reference" dialog, click the "Browse" button.
  3. Browse to the FileUp\dotnet folder to select SAFileup.dll, SAPrgres.dll and FileUpModule.dll files.
2.2 Instruct your web application to use the HttpModule.
Open the web.config file and add the following:
<configuration>
<system.web>
        <httpModules>
<add name="FileUpModule" type="SoftArtisans.Net.FileUpModule,
FileUpModule, Version=$fu.version.module.build$,
Culture=neutral, PublicKeyToken=f593502af6ee46ae"/>
</httpModules>
    </system.web>
<configuration>
2.3 Instruct your application to allow pages with the "uplx" to be processed correctly.
Open the web.config file and add the following:
<configuration>
<system.web>
<httpModules>
<add name="FileUpModule"
type="SoftArtisans.Net.FileUpModule, FileUpModule,
Version=$fu.version.module.build$, Culture=neutral,
PublicKeyToken=f593502af6ee46ae"/>
</httpModules>

<httpHandlers>
<add verb="*" path="*.uplx"
type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>
    </system.web>
<configuration>
2.4 If you are running your application on the 2.0 .NET Framework, add the build provider. This is not necessary for 1.x releases of the .NET Framework.
Open the web.config file and add the following:
<configuration>
<system.web>
        <compilation>
<buildProviders>
<add extension=".uplx"
type="System.Web.Compilation.PageBuildProvider" />
</buildProviders>
</compilation>

        <httpModules>
<add name="FileUpModule" type="SoftArtisans.Net.FileUpModule,
FileUpModule,
Version=$fu.version.module.build$,
Culture=neutral, PublicKeyToken=f593502af6ee46ae"/>
</httpModules>

<httpHandlers>
<add verb="*" path="*.uplx"
type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>
2.5 Set up your application mapping in IIS so that the "*.uplx" extension will be forwarded to ASP.NET for script processing.
  1. Open IIS, right-click your application's virtual directory, and select Properties.
  2. Select the Virtual Directory tab.
  3. Click Configuration.
  4. Select the App Mappings tab.
  5. Click Add.
  6. Browse to aspnet_isapi.dll (typically in [Windows directory]\Microsoft.NET\Framework\[.NET version directory]\).
  7. In the Extension field, enter .uplx.
  8. Select All Verbs.

  9. Check Script Engine, and click OK.

Step 3: Determine the identity under which your application will run.

Identity can be configured in many ways, which is explained in the "Understanding the Concepts" topic, Understanding Permissions(ASP.NET): Determing Identity.

The FileUp Samples application is configured to run as the default account for ASP.NET, "[machine_name]\ASPNET" for Windows 2000 and XP, or "[machine_name]\NETWORK SERVICE" for Windows 2003 Server.

Step 4: Choose where you want to cache and set up appropriate permissions.

Since we are using the HttpModule, we must designate the caching location in the registry. This is done using the FileUpTemp dir registry key whose default value is taken from your system TEMP variable, which is likely to be C:\WINDOWS\TEMP.

To confirm that this is the value set on your web server, please follow the step-by-step instructions for using the Registry Editor as explained in Default Directory for Cached Files

Assuming that C:\WINDOWS\TEMP will be the caching directory, check the NTFS permissions on the directory. Make sure that the ASP.NET machine account has read, write and modify permissions on the directory. For step-by-step instructions on setting these permissions, please see Setting NTFS permissions.

Step 5: Choose where you want to save and set up appropriate permissions.

The Simple Upload sample on which this tutorial is based saves files to a subdirectory of the SAFileUpSamples web application. This is done in order to provide a controlled environment so that the samples will run "out of the box". In a real-life scenario, you will most likely prefer to save to a directory that is not mapped to IIS as a virtual directory. For the sake of keeping in line with this sample, we will check the value of the Path property to determine where the file will be saved:

C#
fileUpload.Path = Page.MapPath(Application["vroot"] + "/temp");

VB.NET
fileUpload.Path = Page.MapPath(Application("vroot").ToString() + _    "/temp")

global.asax
Application["vroot"] = "/SAFileUpSamples";

In a typical installation scenario, this path will resolve to the following physical path:
"C:\Program Files\SoftArtisans\FileUp\samples\temp"

Step 6: Write your code.

The files:

Language File Name Use
C#
simple.uplx
simple.uplx.vb
Presentation
CodeBehind
Location in Samples Directory
FileUp\samples\UploadSamples\Simple\ASPNET\CSharp

Language File Name Use
VB.NET
simple.uplx
simple.uplx.cs
Presentation
CodeBehind
Location in Samples Directory
FileUp\samples\UploadSamples\Simple\ASPNET\VB

In simple.uplx, create an HTML form:

  • The enc-type attribute of the form must be set to "multipart/form-data".
  • The form must contain a control to select a file. This is an input control of the type "file".
  • The form must contain a means of submitting the post to the web server. In this example, an input control of the type "button" is used. The runat attribute is set to run on the server.
  • While not required, it is also helpful to add a means of displaying the information that can be returned in the response. In this example and asp.net literal control is used.

<form id="theForm" runat="server" enctype="multipart/form-data" method="post">

Enter Filename:

<input type="file" id="myFile" name="myFile" />

Click "Browse" to select a file to upload.

<input type="button" id="UploadBtn" runat="server"
OnServerClick="UploadBtn_Click" value="Upload File" />

</form>

<asp:literal id="ltrUploadResults" runat="server" />

When the "Upload File" button is clicked, the form will be posted to the code-behind(simple.uplx.[vb|cs])and the UploadBtn_Click subroutine will be called. It is here that we place the code that we want to process the upload request on the server.

simple.uplx.[vb|cs]: the server-side code.

The FileUp objects are in the SoftArtisans.Net namespace. The objects can be referenced as fully qualified names, such as SoftArtisans.Net.FileUp. To minimize typing and errors, include the SoftArtisans.Net namespace.

C# | using SoftArtisans.Net;
VB.NET | Imports SoftArtisans.Net

Clicking the "Upload File" button sets off the UploadBtn_Click subroutine, where a call is made to ProcesUpload(), which is where the FileUp code has been placed.

C# protected void UploadBtn_Click(object sender, EventArgs e)
{
//--- Hide the form after the upload button is clicked
theForm.Visible = false;
ProcessUpload();
}
VB.NET Protected Sub UploadBtn_Click(sender As Object, _
e As EventArgs)
'--- Hide the form when the upload button is clicked
theForm.Visible = False
ProcessUpload()
End Sub

The ProcessUpload routine contains code that does the the following:

  • Declares FileUp.
  • Sets up a Try..Catch...Finally block.
  • Instantiates FileUp
  • Provides a path for saving.
  • Gets a reference to the file input element in the FileUp form element collection.
  • Saves the file to the file system.
  • Returns information about the file to the Response.
  • Disposes of the FileUp object to free resources.

C# //--- Declare the FileUp object
FileUp fileUpload = null;

//--- This StringBuilder will be used to display results.
System.Text.StringBuilder results = new System.Text.StringBuilder();

try
{
//--- Instantiate the FileUp object
fileUpload = new FileUp (Context);

   //---Set the path property to the location where
//---you would like the file to be saved.
//---The path property takes a physical path,
//---but this sample will save to the FileUp
//---Samples "temp" directory. The MapPath()
//---function converts this relative path to
//---a physical path.
   fileUpload.Path = Page.MapPath (Application["vroot"] +
"/temp");

   //--- Get a reference to the uploaded file field
   SaFile file = (SaFile)fileUpload.Form["myFile"];

   //--- If the file does not exist, FileUp will
//--- throw an error when save() is called.
   if (file != null)
{
if (!file.IsEmpty)
{
file.Save();

      //--- Display information about the saved file.
      results.Append("FileUp Saved the File " +
Successfully.<BR>");

      //--- The full sample code demonstrates
//--- many more properties that can be
//--- used to return information in
//--- the Response.
results.Append("<B>Path on server</B>" +
file.ServerName);
}
}
//--- Display the results on the webform
ltrUploadResults.Text = results.ToString();
}
catch (Exception ex)
{
//--- If an exception is caught, display the details
ltrUploadResults.Text = "<b>An error has occurred: "
</b><br>" + ex.Message;
}
finally
{
//--- Always call Dispose in the finally block
{    if(fileUpload != null)
fileUpload.Dispose();
fileUpload = null;
}
}
VB.NET '--- Declare the FileUp object
Dim fileUpload As FileUp

'--- This StringBuilder will be used to display results.
Dim results As New System.Text.StringBuilder()

Try
'--- Instantiate the FileUp object
fileUpload = New FileUp (Context)

   '---Set the path property to the location where
'---you would like the file to be saved.
'---The path property takes a physical path,
'---but this sample will save to the FileUp
'---Samples "temp" directory. The MapPath() function
'---converts this relative path to a physical path.
   fileUpload.Path = _
Page.MapPath(Application ("vroot").ToString() + _
"/temp")

   '--- Get a reference to the uploaded file field.
Dim file As SaFile = _
CType (fileUpload.Form ("myFile"), SaFile)

   '--- If the file does not exist, FileUp will
'--- throw an error when save() is called.
   If Not (file Is Nothing) Then
If Not (file.IsEmpty) Then
file.Save()

'--- Display information about the saved file
results.Append("FileUp Saved the File " + _
Successfully.<BR>")

'--- The full sample code demonstrates
'--- many more properties that can be used
'--- to return information in the Response.
results.Append("<B>Path on server</B>" + _
file.ServerName )
End If
End If

   '--- Display the results on the webform
   ltrUploadResults.Text = results.ToString()

Catch ex As System.Exception

   '--- If an exception is caught, display the details
   ltrUploadResults.Text = "<b>An error has occurred:" + _
"</b><br>" + ex.Message

Finally

   '--- Always call FileUp.Dispose in the finally block
   If Not (fileUpload Is Nothing) Then
fileUpload.Dispose()
fileUpload = Nothing
End If

End Try

Top


Secure Downloading in ASP

  • The Advantages of Downloading with FileUp
  • The TransferFile Method
  • Setting Response Headers
  • Download and Open in the Browser
  • Downloading with an "Open or Save" Dialog
The Advantages of Downloading with FileUp
  • The files to download do not have to be in a browsable location on the server.

  • The path to the file only exists in the server-side code, which helps protect sensitive information from end-users.

  • Files can be downloaded from any location on the Web server, from a file server, or from a database.

  • FileUp allows you to limit the bandwidth used for downloads per connection and per server.
The behavior of a download is heavily browser-dependent. The only way to ensure that your application works as desired is to extensively test on many different browser platforms. Alternatively, you can use a client-side control such as SoftArtisans XFileto handle your downloads.

Top

The TransferFile Method

FileUp's TransferFilemethod downloads a file from server to browser. TransferFile takes the parameter FileName - the path and name of the file to download. You can set FileName to either a virtual path or a physical path:

TransferFile with a physical path
<% FileUp.TransferFile "c:\folder\sample.doc" %>
TransferFile with a virtual path
<% FileUp.TransferFile server.mappath("sample.doc") %>

The NTFS permissions on the file to be downloaded must be set to allow "Read" access to the identity under which FileUp is running.

To download from a database, use FileUp's TransferBlobmethod.

Top

Setting Response Headers

To let the browser know how to handle a download, you must include three response headers in the download script:

  • Content-type
    The file's MIME content-type, for example, "application/msword".

  • Content-disposition
    If the file's content-disposition is set to "inline", the file will open in the browser. Depending on browser security settings, the user may be prompted with an "open or save" dialog. The user can choose to save to the file system, or open the file directly in the browser, if the browser supports a plug-in associated with that file type.

    If content-disposition is set to "attachment", the browser will open a dialog that asks whether the user wants to open or save the downloaded file. In this situation, the user can either save the file to the file system or open the file in it's native application.

    The content-disposition header also includes the file name.

  • Content-size
    To display an accurate progress indicator when downloading, the browser has to know how many bytes to expect. The content-size header provides this information. In the following examples, we use SoftArtisans FileManagerto obtain the size of the file and set it in the content-size header.

Top

Downloading Large Files

Response buffering is enabled by default in ASP 3.0 and higher. This is not an ideal situation for downloading large files as the entire file will be placed in memory before it is sent to the browser. This may result in memory spikes on the server or the appearance that the browser is hanging, while it waits for the Response from the server.

It is recommended that you disable Response buffering on the page level on those pages that use FileUp to download files. This can be done as follows:

<% @Language="VBScript" %>
<% Response.Buffer = False %>

Add this line near the top of your ASP page. It must occur before any HTML or Response.Write statements. When you disable Response buffering, remove any instances of Response.Clear or Response.Flush from your code as they will cause your script to fail.

Download and Open in the Browser
A download script should not include Response.Write statements or any HTML. If the response includes anything other than the file and response headers, the downloaded file will be corrupted.

The HTTP response's content-disposition header lets the browser know whether to open the downloaded file in the browser, or it's native application. This header also tells the browser the name of the downloaded file. If content-disposition is set to "inline" - as in the following example - the file will open in the browser, provided browser security settings allow this type of action.

<
'--- Instantiate the FileUp object
Set downloadFile = Server.CreateObject("SoftArtisans.FileUp")

'--- Set the path and file name of the file we're going to transfer
strFilePath = Server.MapPath("../sample.doc")
strFileName = "sample.doc"

'--- Set response headers.
'--- FileUp is responsible for reading the file and sending
'--- the raw bytes down to the client through the ASP Response.
'--- For the browserto handle the data properly, the context
'--- of the stream of bytes needs to be established.
'--- This is done with HTTP response headers.

'--- ContentType tells the browser what kind of file is coming.
'--- Application/msword is a Microsoft Word document.
Response.ContentType = "application/msword"

'--- Content-Disposition tells the browser how to handle the file,
'--- and what the name of the file is. The "inline" option tells
'--- the browser to open the Word doc in the browser.
Response.AddHeader "Content-Disposition", "inline;filename=""" & strFileName & """"

'--- To get an accurate progress indicator when downloading,
'--- the browser has to know how many bytes to expect.
'--- Use SoftArtisans.FileManager to obtain the byte-size of the file
'--- and set it in the Content-Size header.
Set fm = Server.CreateObject("SoftArtisans.FileManager")
Set file = fm.GetFile(strFilePath)
Response.AddHeader "Content-Size", file.Size

'--- Download the file.
downloadFile.TransferFile strFilePath
%>

Top

Downloading and Open in the Native Application
A download script should not include Response.Write statements or any HTML. If the response includes anything other than the file and response headers, the downloaded file will be corrupted.

The HTTP response's content-disposition header lets the browser know whether to open the downloaded file in the browser, or open the file in the file's native application. If content-disposition is set to "attachment" - as in the following example - the browser will display a dialog that asks the user to open or save the file. Choosing "open" will result in the file being opened in its native application. Choosing "save" allows the user to save the file to the file system.

This header also tells the browser the name of the downloaded file.

<%
'--- Instantiate the FileUp object.
Set downloadFile = Server.CreateObject("SoftArtisans.FileUp")

'--- Set the path and file name of the file we're going to transfer.
strFilePath = Server.MapPath("../sample.doc")
strFileName = "sample.doc"

'--- Set response headers.
'--- FileUp is responsible for reading the file and sending
'--- the raw bytes down to the client through the ASP Response.
'--- For the browser to handle the data properly, the context
'--- of the stream of bytes needs to be established.
'--- This is done with HTTP response headers.

'--- ContentType tells the browser what kind of file is coming.
'--- Application/x-msdownload is a special type that
'--- "should" prompt the user with a save-as dialog every time.
Response.ContentType = "application/x-msdownload"

'--- Content-Disposition tells the browser how to
'--- handle the file, and what the name
'--- of the file is.
Response.AddHeader "Content-Disposition", "attachment;filename=""" & strFileName & """"

'--- In order to get an accurate progress indicator when downloading,
'--- the browser has to know how many bytes to expect.
'--- Use SoftArtisans FileManager to obtain the byte-size of the file
'--- and set it in the Content-Size header
Set fm = Server.CreateObject("SoftArtisans.FileManager")
Set file = fm.GetFile(strFilePath)
Response.AddHeader "Content-Size", file.Size

'--- Download the file.
downloadFile.TransferFile strFilePath
%>

Top


Secure Downloading in ASP.NET

  • The Advantages of Downloading with FileUp
  • The TransferFile Method
  • Setting Response Headers
  • Download and Open in the Browser
  • Downloading with an "Open or Save" Dialog
The Advantages of Downloading with FileUp
  • The files to download do not have to be in a browsable location on the server.

  • The path to the file only exists in the server-side code, which helps protect sensitive information from end-users.

  • Files can be downloaded from any location on the Web server, from a file server, or from a database.

  • FileUp allows you to limit the bandwidth used for downloads per connection and per server.
The behavior of a download is heavily browser-dependent. The only way to ensure that your application works as desired is to extensively test on many different browser platforms. Alternatively, you can use a client-side control such as SoftArtisans XFileto handle your downloads.

Top

The TransferFile Method

FileUp's TransferFilemethod downloads a file from server to browser. TransferFile takes the parameter FileName - the path and name of the file to download. The path must be a physical path, but you can set FileName to virtual path using MapPath().

TransferFile with a physical path
C# | FileUp.TransferFile("c:\\folder\\sample.doc");
VB.NET | FileUp.TransferFile("c:\folder\sample.doc")
TransferFile with a virtual path
C# FileUp.TransferFile(Page.MapPath(Application["vroot"].ToString() +
"/sample.doc"));
VB.NET FileUp.TransferFile(Page.MapPath(Application("vroot").ToString() + _
"/sample.doc"))

The NTFS permissions on the file to be downloaded must be set to allow "Read" access to the identity under which FileUp is running.

To download from a database, use FileUp's TransferBlobmethod.

Top

Setting Response Headers

To let the browser know how to handle a download, you must include three response headers in the download script:

  • Content-type
    The file's MIME content-type, for example, "application/msword".

  • Content-disposition
    If the file's content-disposition is set to "inline", the file will open in the browser. Depending on browser security settings, the user may be prompted with an "open or save" dialog. The user can choose to save to the file system, or open the file directly in the browser, if the browser supports a plug-in associated with that file type.

    If content-disposition is set to "attachment", the browser will open a dialog that asks whether the user wants to open or save the downloaded file. In this situation, the user can either save the file to the file system or open the file in it's native application.

    The content-disposition header also includes the file name.

  • Content-size
    To display an accurate progress indicator when downloading, the browser has to know how many bytes to expect. The content-size header provides this information. In the following examples, we use the .NET System.IO.FileInfo class to obtain the size of the file and set it in the content-size header.

Top

Downloading Large Files

Response buffering is enabled by default in ASP.NET. This is not an ideal situation for downloading large files as the entire file will be placed in memory before it is sent to the browser. This may result in memory spikes on the server or the appearance that the browser is hanging, while it waits for the Response from the server.

It is recommended that you disable Response buffering on the page level on those pages that use FileUp to download files. This can be done as follows:

C# | Response.Buffer = false;
VB.NET | Response.Buffer = false

Add this line near the top of your response output logic. It must occur before any HTML or Response.Write statements. When you disable Response buffering, remove any instances of Response.Clear or Response.Flush from your code as they will cause your script to fail.

Download and Open in the Browser
A download script should not include Response.Write statements or any HTML. If the response includes anything other than the file and response headers, the downloaded file will be corrupted.

The HTTP response's content-disposition header lets the browser know whether to open the downloaded file in the browser, or it's native application. This header also tells the browser the name of the downloaded file. If content-disposition is set to "inline" - as in the following example - the file will open in the browser, provided browser security settings allow this type of action.

C# - Download and Open in Browser
private void DownloadFile()
{
    //--- Disable Response buffering if downloading a large file.     Response.Buffer=False;

    //--- Declare the FileUp object
FileUp fileDownload = null;

try
{
        //--- Instantiate the FileUp object
fileDownload = new FileUp (Context);

        //--- Set the path and filename of the file
//--- we're going to transfer.
        string strFilePath;
strFilePath = "C:\\folder\\sample.doc";
string strFileName = "sample.doc";

        //--- Set response headers.
//--- FileUp is responsible for reading the file
//--- and sending the raw bytes
//--- down to the client through the Response.
//--- In order for the browser
//--- to handle the data properly, the context of
//--- the anonymously streaming bytes
//--- needs to be established.
//--- This is done with HTTP response headers.

//--- ContentType tells the browser what kind of file is coming.
//--- application/msword is a Microsoft Word document
        Response.ContentType = "application/msword";

        //--- Content-Disposition tells the browser how to
//--- handle the file, and what the name
//--- of the file is. The "inline" option tells the browser
//--- to open the Word doc in the browser plug-in.
        Response.AddHeader("Content-Disposition", "inline;filename=\""
+ strFileName + "\"");
Response.AddHeader("Content-Length",
new System.IO.FileInfo(strFilePath).Length.ToString());

        //--- Call FileUp.TransferFile and pass the full file path
//--- to begin downloading the file
        fileDownload.TransferFile(strFilePath);
Page.Response.SuppressContent = true;

}
catch (Exception ex)
{
        //--- If an exception is caught, display a message
        Page.Response.ClearHeaders();
Page.Response.Write("<b>An exception has occurred " +
"when downloading the file</b> <br>" +
ex.Message);
}
finally
{
        //--- Always call FileUp.Dispose in the finally block
        if(fileDownload != null)
{
fileDownload.Dispose();
fileDownload = null;
}
}
}
VB.NET - Download and Open in Browser
Private Sub DownloadFile()

    '--- Disable Response buffering if downloading a large file.
Response.Buffer = False

    '--- Declare the FileUp object
Dim fileDownload As FileUp

Try
        '--- Instantiate the FileUp object
      fileDownload = New FileUp (Context)

        '--- Set the path and filename of the file
'--- we're going to transfer.
Dim strFilePath As String
strFilePath = "C:\folder\sample.doc"
Dim strFileName As String = "sample.doc"

        '--- Set response headers.
'--- FileUp is responsible for reading the file
'--- and sending the raw bytes
'--- down to the client through the Response.
'--- In order for the browser
'--- to handle the data properly, the context of
'--- the anonymously streaming bytes
'--- needs to be established.
'--- This is done with HTTP response headers.

'--- ContentType tells the browser what kind of file is coming.
'--- application/msword is a Microsoft Word document
        Response.ContentType = "application/msword"

        '--- Content-Disposition tells the browser how to
'--- handle the file, and what the name
'--- of the file is. The "inline" option tells the browser
'--- to open the Word doc in the browser plug-in.
        Response.AddHeader("Content-Disposition", _
"inline;filename=""" + strFileName + """")
Response.AddHeader("Content-Length", _
New System.IO.FileInfo(strFilePath).Length.ToString())

        '--- Call FileUp.TransferFile and pass the full file path
'--- to begin downloading the file
        fileDownload.TransferFile(strFilePath)
Page.Response.SuppressContent = true

Catch ex As System.Exception
        '--- If an exception is caught, display a message
        Page.Response.ClearHeaders()
Page.Response.Write("<b>An exception has occurred " + _
"when downloading the file</b><br>" + _
ex.Message)

Finally
        '--- Always call FileUp.Dispose in the finally block
        If Not (fileDownload Is Nothing) Then
fileDownload.Dispose()
fileDownload = Nothing
End If
End Try

End Sub

Top

Download and Open in the Native Application
A download script should not include Response.Write statements or any HTML. If the response includes anything other than the file and response headers, the downloaded file will be corrupted.

The HTTP response's content-disposition header lets the browser know whether to open the downloaded file in the browser, or open the file in the file's native application. If content-disposition is set to "attachment" - as in the following example - the browser will display a dialog that asks the user to open or save the file. Choosing "open" will result in the file being opened in its native application. Choosing "save" allows the user to save the file to the file system.

This header also tells the browser the name of the downloaded file.

C# - Download and Open in the Native Application
private void DownloadFile()
{
    //--- Disable Response buffering if downloading a large file.     Response.Buffer=False;

    //--- Declare the FileUp object
FileUp fileDownload = null;

try
{
        //--- Instantiate the FileUp object
fileDownload = new FileUp (Context);

        //--- Set the path and filename of the file
//--- we're going to transfer.
        string strFilePath;
strFilePath = "C:\\folder\\sample.doc";
string strFileName = "sample.doc";

        //--- Set response headers.
//--- FileUp is responsible for reading the file
//--- and sending the raw bytes
//--- down to the client through the Response.
//--- In order for the browser
//--- to handle the data properly, the context of
//--- the anonymously streaming bytes
//--- needs to be established.
//--- This is done with HTTP response headers.

//--- ContentType tells the browser what kind of file is coming.
//--- application/msword is a Microsoft Word document
        Response.ContentType = "application/msword";

        //--- Content-Disposition tells the browser how to
//--- handle the file, and what the name
//--- of the file is. The "attachment" option tells the browser
//--- to open the Word doc in a new instance of Microsoft Word,
//--- not in the browser Word plug-in
        Response.AddHeader("Content-Disposition",
"attachment;filename=\"" + strFileName + "\"");
Response.AddHeader("Content-Length",
new System.IO.FileInfo(strFilePath).Length.ToString());

        //--- Call FileUp.TransferFile and pass the full file path
//--- to begin downloading the file
        fileDownload.TransferFile(strFilePath);
Page.Response.SuppressContent = true;

}
catch (Exception ex)
{
        //--- If an exception is caught, display a message
        Page.Response.ClearHeaders();
Page.Response.Write("<b>An exception has occurred " +
"when downloading the file</b> <br>" +
ex.Message);
}
finally
{
        //--- Always call FileUp.Dispose in the finally block
        if(fileDownload != null)
{
fileDownload.Dispose();
fileDownload = null;
}
}
}
VB.NET - Download and Open in the Native Application
Private Sub DownloadFile()

    '--- Disable Response buffering if downloading a large file.
Response.Buffer = False

    '--- Declare the FileUp object
Dim fileDownload As FileUp

Try
        '--- Instantiate the FileUp object
fileDownload = New FileUp (Context)

        '--- Set the path and filename of the file
'--- we're going to transfer.
Dim strFilePath As String
strFilePath = "C:\folder\sample.doc"
Dim strFileName As String = "sample.doc"

        '--- Set response headers.
'--- FileUp is responsible for reading the file.
'--- and sending the raw bytes
'--- down to the client through the Response.
'--- In order for the browser
'--- to handle the data properly, the context of
'--- the anonymously streaming bytes
'--- needs to be established.
'--- This is done with HTTP response headers.

'--- ContentType tells the browser what kind of file is coming.
'--- application/msword is a Microsoft Word document
        Response.ContentType = "application/msword"

        '--- Content-Disposition tells the browser how to
'--- handle the file, and what the name
'--- of the file is. The "attachment" option tells
'--- the browser to open the Word doc
'--- in a new instance of Microsoft Word,
'--- not in the browser Word plug-in.
        Response.AddHeader("Content-Disposition", _
"attachment;filename=""" + strFileName + """")
Response.AddHeader("Content-Length", _
New System.IO.FileInfo(strFilePath).Length.ToString())

        '--- Call FileUp.TransferFile and pass the full file path
'--- to begin downloading the file
        fileDownload.TransferFile(strFilePath)
Page.Response.SuppressContent = true

Catch ex As System.Exception
        '--- If an exception is caught, display a message
        Page.Response.ClearHeaders()
Page.Response.Write("<b>An exception has occurred " + _
"when downloading the file</b><br>" + _
ex.Message)

Finally
        '--- Always call FileUp.Dispose in the finally block
        If Not (fileDownload Is Nothing) Then
fileDownload.Dispose()
fileDownload = Nothing
End If
End Try

End Sub

Top


Programmer's Guide for ASP

  • Preserving the User's Original File Name
  • Adding a Second File
  • Accessing Multiple Form Elements
  • Limiting the Upload Size
  • Restricting File Types
  • Adding a Server-Side Progress Indicator
  • Multilingual Support


Preserving The User's Original File Name

This sample builds on the code developed in the "Getting Started" chapter, in the example, "A Simple Upload in ASP". It assumes that you already understand how to configure your application and that you know how to perform at least a simple upload.

In the "Simple Upload in ASP" sample, the code is set up to save the uploaded file with a new name. In this example, you will see how to preserve the original file name, as it was named on the client file system.

The user's original file name and path on the client is automatically sent by the browser when the form is uploaded. When FileUp parses the request, it is able to read in this information. If you choose to call the Save method on the file, FileUp preserves the original file name. The directory to which the file is saved will be retrieved from the path property setting.
The Client Code
<html>

<head>
<title>Please Upload Your File</title>
</head>

<body>

<form enctype="multipart/form-data" method="post"
action="formresp.asp">

Enter filename to upload:
<input type="file" id="myFile" name="myFile"><br />
<input type="submit" />

</form>
</body>
</html>

Here's how we can preserve the user's original filename:

The Server Code
<%@ language="vbscript" %>
<html>

<head>
<title>Upload File Results</title>
</head>

<body>
<%
Dim fileUpload
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

fileUpload.Path = "C:\Temp"

'--- Check to be sure there was a file selected in the form
'--- If so, continue processing
If IsObject(fileUpload.Form("myFile")) Then
If Not fileUpload.Form("myFile").IsEmpty Then

fileUpload.Form("myFile").Save

Response.Write "FileUp Saved the File Successfully."
Else
Response.Write "There was no file submitted in the form field."
End If
Else
Response.Write "The referenced field does not exist " & _
"or is not of type=""file"""
End If

'--- Dereference FileUp
Set fileUpload = Nothing
%>
</body>
</html>

The Save method does not take any parameters. To set the upload's destination directory, you must set the Pathproperty. The Path property sets the directory on the Web server in which to cache and/or save uploaded files.

Alternately, you can preserve the original file name if you call SaveAs() and append the value of ShortFileName property.

<%
file.SaveAs("C:\MyDirectory\" & file.ShortFileName)
%>
Taking the Lesson Further...
  • To discover the original name of the file before saving, use the ShortFileName property.

  • If you would like to verify the client-side path in addition to the original file name, use the UserFileName property instead.

  • If you are preserving the user's original file name, you may want to instruct FileUp how to handle situations where the uploaded file has the same name as a file that already exists in your upload directory. By default, FileUp will overwrite the existing file with the new file. You can change this behavior by using one of the following strategies:

    • Set FileUp's OverwriteFiles property to "False" so that an error can be raised.

    • Set FileUp's CreateNewFile property to "True" so that FileUp can automatically handle a situation of a pre-existing file by renaming the new file by appending an underscore and a number between 0 and 999 to the file's name.

Top


Adding a Second File

You've now seen how to upload a file and capture additional form elements. What if you wanted to transmit multiple files with a single form submit?

To add an additional file, just add another <input type="file">tag to your form.

Although the Internet standard specification for HTTP upload (RFC 1867 [image]) permits filenames with wildcards(for example, "*.doc"), neither Netscape nor Microsoft Internet Explorer support names with wildcards at this time. When they do, FileUpwill be able to process file names with wildcards uploaded from Netscape and IE. The client-side tool SoftArtisans XFile [image] supports uploading wildcards from the client.

Without using a client-side tool like XFile, it is necessary to add an additional <input type="file"> tag to the form for every file you want to upload.

Here is an example:

The Client Code
<html>

<head>
<title>Please Upload Your File</title>
</head>

<body>

<form enctype="multipart/form-data" method="post"
action="formresp.asp">

Enter filename to upload:
<input type="file" id="myFile" name="myFile" /><br />

Enter a second filename to upload:
<input type="file" id="myFile2" name="myFile2" /><br />

<input type="submit" />

</form>
</body>
</html>

formresp.asp contains the following code:

The Server Code
<%@ language="vbscript" %>
<html>

<head>
<title>Upload File Results</title>
</head>

<body>

<%
Dim fileUpload
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

fileUpload.Path = "C:\Temp"

'--- Check to be sure there was a file selected in the form
'--- If so, continue processing
If IsObject(fileUpload.Form("myFile")) Then
If Not fileUpload.Form("myFile").IsEmpty Then

fileUpload.Form("myFile").Save

'--- Display information about the saved file
Response.Write "FileUp saved the first file successfully.<BR>"
Response.Write "The file has been saved to: " & _
fileUpload.Form("myFile").ServerName & " <BR>"
Else
Response.Write "There was no file submitted " & _
"in the first form field."
End If
Else
Response.Write "The first referenced field does not exist" & _
" or is not of type=""file"""
End If

If IsObject(fileUpload.Form("myFile2")) Then
If Not fileUpload.Form("myFile2").IsEmpty Then

fileUpload.Form("myFile2").Save

'--- Display information about the saved file
Response.Write "FileUp saved the second file successfully.<BR>"
Response.Write "The file has been saved to: " &_
fileUpload.Form("myFile2").ServerName & " <BR>"
Else
Response.Write "There was no file submitted " & _
"in the second form field."
End If
Else
Response.Write "The second referenced field does not exist" & _
" or is not of type=""file"""
End If

'--- Dereference FileUp
Set fileUpload = Nothing
%>

</body>
</html>

In this case, we are referring to the file elements explicitly by name:

fileUpload.Form("myFile").Save
...
fileUpload.Form("myFile2").Save

Like when referring to other form elements, use the syntax fileUpload.Form(Form Element Name) to refer to the value of the file. If you use fileUpload.Savewithout specifying the file's form element name, the method call would refer to the first file element that was found. This is ambiguous. So, when uploading multiple files, be explicit and use the fileUpload.Form(Form Element Name) syntax.

All of the methods and properties (such as TotalBytes) are available when using this syntax. For example, to list the total number of bytes for the first file, you could use the following line of code:

Total Bytes Written for File 1: <%=fileUpload.Form("myFile").TotalBytes%>
Total Bytes Written for File 2: <%=fileUpload.Form("myFile2").TotalBytes%>

Internally, FileUphas created an instance of an SAFileobject to represent each uploaded file. The code above, could also be written as such:

For Each strFormElement In fileUpload.Form

'--- If it's a file, IsObject() will return True
'--- if it's a conventional form element, it will be false
If IsObject(fileUpload.Form(strFormElement)) Then

'--- It's a file element, so we'll see if it's empty or not
If Not fileUpload.Form(strFormElement).IsEmpty Then

'--- It's not empty, so we'll save it
fileUpload.Form(strFormElement).Save
Else
...
End If
...
End If
Next

Summary

  • If there are multiple file elements on the form, call the Save method from each file object or loop through the entire file collection.

  • For each uploaded file, FileUpcreates a new SAFile object to represent the uploaded file.

Top


Accessing Multiple Form Elements

In the Simple Upload example in the Getting Started chapter, a form was used that only contained one file input element. However, most people want to capture additional information on the form, such as a description, along with the file.

Normally, you can use ASP's Request.Form object to access these other elements on the form. However, when uploading files, you must change the Encoding Type of the HTML form to "multipart/form-data". The ASP Request.Form object does not understand data transmitted using this encoding type.

FileUpprovides a Formobject that provides identical functionality to the ASP Request.Form object, but can understand the encoding type that is specific to file uploads.

FileUp also provides the FormExobject, which handles collections of form elements (listboxes, radio buttons, multiple files, etc.). To access the elements of a FormEx collection use either:

  • A "For...Each" statement. For example: "For each item in fileUpload.FormEx(multipart)"

    OR

  • Index numbers. For example: "FormEx("name").index"

Here is an example:

The Client Code
<html>

<head>
<title>Please Upload Your File</title>
</head>

<body>

<form enctype="multipart/form-data" method="post"
action="formresp.asp">

Enter description:
<input type="text" id="descrip" name="descrip" /><br />

Enter filename to upload:
<input type="file" id="myFile" name="myFile" /><br />

<input type="submit" />

</form>
</body>
</html>

formresp.asp contains the following code:

The Server Code
<%@ language="vbscript" %>
<html>

<head>
<title>Upload File Results</title>
</head>

<body>

<%
Dim fileUpload
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

fileUpload.Path = "C:\Temp"

'--- Check to be sure there was a file selected in the form
'--- If so, continue processing
If IsObject(fileUpload.Form("myFile")) Then
If Not fileUpload.Form("myFile").IsEmpty Then

fileUpload.Form("myFile").Save

'--- Display information about the saved file
Response.Write "FileUp Saved the File Successfully.<br />"

      Response.Write "The file has been saved to: " &_
fileUpload.Form("myFile").ServerName & " <br />"

Response.Write "The description you entered was: " &_
fileUpload.Form("descrip")
   Else
Response.Write "There was no file submitted in the form field."
End If
Else
Response.Write "The referenced field does not exist " & _
"or is not of type=""file"""
End If

'--- Dereference FileUp
Set fileUpload = Nothing
%>

</body>
</html>

In this case, the definition of the form still uses enctype="multipart/form-data", but now there is an additional form element containing a text box.

Enter description: <input type="text" id="descrip" name="descrip" />

Let's look at the form's processing (formresp.asp).

In the upload processing script (formresp.asp), we refer to the form element (the text box) explicitly by name via the FileUp Form collection:

Response.Write "The description you entered was: " & fileUpload.Form("descrip")

As you add more form elements to your page, the above approach may be inconvenient. You can instead loop through FileUp's form collection, saving out files and accessing non-file form elements with simple testing. Note the use of FormEx, which handles non-file elements that may have multiple values, such as mult-select controls.

'--- Declarations
Dim fileUpload
Dim strFormElement
Dim strSubItem
Dim i

'--- Instantiate the FileUp object
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

fileUpload.Path = C:\TEMP
Response.Write "<h3>Upload Results</h3>"
'--- This main loop will iterate through every submitted form element
'--- Within the loop, we'll test it to see if it's a file or a text form
'--- element. If it's a text form element, we'll see if it's a single-value
'--- or a subcollection

For Each strFormElement In fileUpload.Form

'--- If it's a file, IsObject() will return true
'--- if it's a conventional form element, it will be false
If IsObject(fileUpload.Form(strFormElement)) Then

'--- It's a file element, so we'll see if it's empty or not
If Not fileUpload.Form(strFormElement).IsEmpty Then

'--- It's not empty, so we'll save it
fileUpload.Form(strFormElement).Save
Else

'--- It's empty, just write a message
Response.Write "No file submitted."
End If

'--- If it's not a file, it's a conventional text-based form element
Else
'--- It's a subcollection, we'll need to loop again
'--- to retrieve the values of the subcollection here
'--- Note how we need to use FormEx to determine if it's a subcollection
'--- always use FormEx when using, or if anticipating using, subcollections!
If fileUpload.FormEx(strFormElement).Count > 1 Then

Response.Write "Subcollection:" & strFormElement & "<br />"
i = 1
'--- Loop through the subcollection
For Each strSubItem In fileUpload.FormEx(strFormElement)
Response.Write i & ": " & strSubItem & "<br />"
i = i + 1
Next
Response.Write "<br /><br />"
Else

'--- It's just a single value, not a subcollection
'--- simply display the single value
Response.Write "Form single value:" & strFormElement & _
fileUpload.Form(strFormElement) & "<br />"
End If

End If

Response.Write "<hr />"
Next

'--- Dereference FileUp
Set fileUpload = Nothing

The following figure shows how you could put these form elements together into an application. You will find ASP and ASP.NET applications that demonstrate uploading with additional form elements in FileUp\Samples\UploadSamples\FileAndForm.

Summary

  • Even if there are multiple form elements, you must still use:

    • <form enctype="multipart/form-data" ... >

  • ASP's Request.Form object does not understand this encoding type. Instead use, FileUp's Form object or - for collections - the FormExobject.

  • To refer to form elements, use the name of the element, for example, fileUpload.Form("descrip")

Top


Limiting the Upload Size

You've seen how to upload multiple files and access each of their individual properties, as well as how to read properties of the file, such as the TotalBytesof the upload.

There are several properties that can be set as well. One very useful property is MaxBytes. MaxBytesallows you to set a firm limit on the size of the uploaded file, ensuring that malicious users do not fill up your server's hard disk with huge files.

When you set the MaxBytes property, FileUpwill write up to the number of bytes you specify and then stop. Any additional data will be discarded. You can set MaxBytes once and it will apply to all files in the current upload, limiting each of them to the value that you specify.

The default value of the MaxBytes property is zero (0). fileUpload.MaxBytes = 0 When MaxBytes is set to its default value of zero, there is no limit on the size of files that can be uploaded.

Set MaxBytes before referencing any form elements.

As soon as a form element is referenced, FileUp will cache the upload on the server. If you set MaxBytes after referencing a form element, by the time the MaxBytes property is set, the upload will have been cached. Note: if you set MaxBytes after referencing a form element, but before saving the uploaded files, MaxBytes will take effect when you save.

In the following example, we use the same simple form used in the first upload :

The Client Code
<html>

<head>
<title>Please Upload Your File</title>
</head>

<body>

<form enctype="multipart/form-data" method="post"
action="formresp.asp">

Enter filename to upload:
<input type="file" id="myFile" name="myFile" /><br />

A file larger than 1000 bytes will be truncated on the server.<br />
<input type="submit" />

</form>
</body>
</html>

Here is the response file, formresp.asp:

The Server Code
<%@ language="vbscript" %>
<html>

<head>
<title>Upload File Results</title>
</head>

<body>
<%
Dim fileUpload
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

fileUpload.Path = "C:\Temp"
fileUpload.MaxBytes = 1000

'--- Check to be sure there was a file selected in the form
'--- If so, continue processing
If IsObject(fileUpload.Form("myFile")) Then
If Not fileUpload.Form("myFile").IsEmpty Then

fileUpload.Form("myFile").Save

Response.Write "FileUp Saved the File Successfully." & "<br />
Response.Write "Total Bytes sent by the browser: " & Request.TotalBytes & _
" <br /> "
Response.Write "Total Bytes Saved: " & _
fileUpload.Form("myFile").TotalBytes & "<br />"
Else
Response.Write "There was no file submitted in the form field."
End If
Else
Response.Write "The referenced field does not exist " & _
"or is not of type=""file"""
End If

'--- Dereference FileUp
Set fileUpload = Nothing
%>
</body>
</html>

In the upload processing script (formresp.asp), MaxBytes is set to 1000. That means that FileUp will save up to 1000 bytes of each uploaded file. If you try to upload a file larger than 1000 bytes, notice that only the first 1000 bytes would be written to the hard disk. No error will be raised, indicating that the file was truncated.

MaxBytes is Read/Write property, meaning that it is possible to both set its value and retrieve its value.

Because the MaxBytes setting truncates the file without raising an error, the server code is set up to display the number of bytes sent by the browser in comparison to the number of bytes actually saved on the server. This is a comparison between Request.TotalBytes and FileUp's TotalBytes property.

You may have noticed that the total number of bytes transmitted by you is larger than your original file's size on the client file system. This is normal, since the browser must add information such as headers and encoding information. Request.TotalBytesreports the total including the file, encoding information, and other form elements that may be present.

Summary

  • It is possible to limit the size of the upload by using the MaxBytesproperty.

  • The amount of information transmitted by the browser is always larger than the file alone because of additional encoding information and form elements.

  • MaxBytes does not raise an error when it truncates files.

See also, MaxBytesToCancel.

Top


Restricting File Types

There are times when you may need to restrict the type of files saved on the Web server. You can do so by using FileUp's ContentTypeproperty and a Select condition to save only files that are a certain type.

Once your file is uploaded, you would include the following after creating an instance of FileUp:

Server-Side Code
<%
'--- Get the uploaded file's content-type and
'--- assign it to a variable.
FCONT = fileUpload.ContentType

'--- Use the Select Case Condition to restrict the file type.
Select Case LCase(FCONT)
Case "image/gif"
fileUpload.Save
Response.Write "<P>" & fileUpload.ShortFileName & " has been saved."

Case "image/pjpeg"
fileUpload.Save
Response.Write "<P>" & fileUpload.ShortFileName & " has been saved."

Case Else
fileUpload.delete
Response.Write "<P>" & "You can only upload gif and jpeg files.<br />"
Response.End
End Select
....
%>

We get the media content-type of the file uploaded by using the ContentTypeproperty. In this example, we accept only .gif and .jpeg files. So we are looking for either "image/pjpeg" or "image/gif" as the media content-type.

A Case condition statement is used to save the correct file and send a successful response. Notice that the property ShortFileNameis used to supply the name of the file that was saved. If the file type is incorrect, the file will be deleted and an error response will sent.

Summary

  • To restrict a file by media type, identify the media content of an uploaded file using the ContentTypeproperty, and use a Select Case condition statement.

  • Alternately, to restrict a file by file name extension, identify a file's original name, without the original path, by using ShortFileNameand parsing for the extension.

  • To restrict the types of files to be uploaded before they leave the client, consider using an intelligent client such as SoftArtisans XFile. Please see Restricting File Size and Type Before Uploading.

Top


Adding a Server-Side Progress Indicator

FileUp includes a server-side progress indicator that can be displayed to the user using HTML. The server-side progress indicator lets you know how much of the entire upload has arrived at the server. In an upload from the browser to an ASP page, include the progress indicator in a separate page. In this page, you can get and display to the user:

  • The Percentageof the upload that has reached the server.
  • TotalBytesin the upload.
  • TransferredBytesso far.

You can use HTML techniques to customize the output effect, and display a counter or a progress bar.

EnableSessionState Directive

The progress indicator needs to operate outside of the current session in order to refresh properly. In order to maintain session state, ASP must serialize all requests for that session. To allow the progress indicator to execute outside of a session, the following directive must be added to the progress indicator page:

<%@ ENABLESESSIONSTATE=False %>

Setting the EnableSessionState directive to False allows the progress indicator page's request to be processed on a separate thread. This allows the progress indicator to update itself while the upload continues to be processed on another thread. If this directive is not set, or is set to true, then the progress indicator is queued until the upload finishes. At this point, the progress indicator can now be updated, but the upload is complete, so the indicator jumps immediately from 0% to 100%.

The upload form and processing page can participate in the session as usual.

Example

The following lines are from an application that contains three scripts: form.asp, formresp.asp and progress.asp. Form.asp submits the file to the upload processing page formresp.asp. Progress.asp contains the progress indicator.

Form.asp
...
<%
'--- Instantiate the FileUpProgress object.
Set progress = Server.CreateObject("SoftArtisans.FileUpProgress")

'--- Get the next available progress ID.
'--- The progress ID is how the progress indicator and FileUp
'--- sychronize with each other.
intProgressID = progress.NextProgressID
%>
...
<head>
<script language="javascript">
<i>/*
This function makes sure that the progress indicator and server-side
processing page receive the new progress ID we just created. Also, it pops up the
progress window.
*/</i>
function startupload() {
winstyle="height=150,width=500,status=no,_       toolbar=no,menubar=no,location=no";
window.open("progress.asp?progressid=<%=intProgressID%>",_       "_blank",winstyle);
document.theForm.action="formresp.asp?progressid=<%=intProgressID%>";
}
</script>
</head>
<body>
...
<form onSubmit="startupload();" id="theForm"
name="theForm" action="formresp.asp"
enctype="multipart/form-data" method="post">
<p>Enter Filename:</p>
<input type="file" id="myFile" name="myFile" />
<p>Click "Browse" to select a file to upload</p>
<input type="submit" id="sub1" name="sub1" value="Upload File" />
</form>
...

Formresp.asp
<%
'--- Instantiate the FileUp object
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Assign the same progress ID that we assigned to the progress object
fileUpload.ProgressID = CInt(Request.QueryString("progressid"))

fileUpload.Path = "C:\temp"
...
fileUpload.Form("myFile").Save
...
%>

Progress.asp
<%@ language=VBScript ENABLESESSIONSTATE=False %>
<%
'-----------------------------------------------------------------------
'--- This is the progress indicator itself. It refreshes every second
'--- to re-read the file progress properties, which are updated thoughout
'--- the upload.
'-----------------------------------------------------------------------
'--- Declarations
Dim progress
Dim intProgressID
Dim intPercentComplete
Dim intBytesTransferred
Dim intTotalBytes
Dim bDone

intPercentComplete = 0
intBytesTransferred = 0
intTotalBytes = 0

'--- Instantiate the FileUpProgress object
Set progress = Server.CreateObject("Softartisans.FileUpProgress")

'--- Set the ProgressID with the value we submitted from the form page
progress.ProgressID = CInt(Request.QueryString("progressid"))

'--- Read the values of the progress indicator's properties
intPercentComplete = progress.Percentage
intBytesTransferred = progress.TransferredBytes
intTotalBytes = progress.TotalBytes

%>
<html>
<head>
<%
'--- If the upload isn't complete, continue to refresh
If intPercentComplete < 100 Then
bDone = False
Response.Write("<meta http-equiv=""Refresh"" content=1>")
Else
bDone = True
End If
%>
</head>
<body>
<table border="1">
<tr>
<td colspan="3"><b>FileUp Progress Indicator</b></td>
<td colspan="2"><b>Status:
<%
If bDone Then
Response.Write("Complete!")
Else
Response.Write("Sending")
End If
%>
</b></td>
</tr>
<tr>
<td>Progress ID </td>
<td>Graphic Indicator</td>
<td>Transferred Bytes</td>
<td>Total Bytes</td>
<td>Transferred Percentage</td>
</tr>
<tr>
<td align="left"><%=progress.progressid%></td>
<td>
<table bordercolor="black" border="1" cellspacing="0"
align="left" width="<%=intPercentComplete%>%">
<tr>
<td align="right" width="100%" bgcolor="blue">
<B><%=intPercentComplete%></b></td>
</tr>
</table>
<%
Response.Write("</td>")
Response.Write "<td align="center">" & intBytesTransferred & "</td>"

If progress.TotalBytes > 0 Then
Response.Write("<td align="center">" & intTotalBytes & "</td>" & _
"<td align="center">" & intPercentComplete & "%</td>" )
Else
Response.Write ("<td align="center">" & "N/A" & "</td>" & _
"<td align="center">" & "N/A" & "</td>")
End If

%>
</tr>
</table>
</body>
</html>

Top


Multilingual Support

Unicode Support

Internally, computers store all characters (letters, numbers, and symbols) as numbers. In the past, each language used one or more encoding system to assign a unique number to each character. The various single-language encoding systems are not consistent. For example, two encoding systems may assign two different numeric values to the same letter, or assign the same numeric value to two different letters. Since the various encoding systems conflict with each other, data is easily corrupted when passed between language platforms.

Unicode is a single encoding standard for all languages. Unicode assigns a unique number to each character, and the same number to identical characters in different languages. For example, the letter h has the same Unicode value for each character set (language) that contains it.

SoftArtisans FileUp is Unicode compliant, enabling the transfer of data between systems, regardless of language, without the risk of data corruption. By setting FileUp's Codepage property, you will be able to preserve file names in their original language.

Codepage and Charset

To preserve file names when transferring files between language platforms, set the following properties.

  • Codepage
    FileUp's Codepage property contains a Unicode language code for correctly storing the file name internally.

  • Charset
    The HTML <meta> tag's Charset attribute specifies a Unicode language code for correctly displaying the file name. To set Charset, set the http-equiv attribute to "Content-Type" and set the content attribute to the appropriate character set identifier, as in the example below.

If, for example, you are uploading a file with a Japanese name,

  1. In your request script, set

    • <meta http-equiv="Content-Type" content="text/html;
      charset=iso-2022-jp" />       , and
  2. In your FileUp response script, set

    • <meta http-equiv="Content-Type" content="text/html;
      charset=iso-2022-jp" />       , and
    • fileUpload.CodePage = 50220

For a complete list of CodePage and Charset values, see Microsoft's Character Set Recognition [image] reference.

Top


Programmer's Guide for ASP.NET

  • Preserving the User's Original File Name
  • Adding a Second File
  • Accessing Multiple Form Elements
  • Limiting the Upload Size
  • Restricting File Types
  • Adding a Server-Side Progress Indicator
  • Multilingual Support
  • Using FileUp with ADO.NET


Preserving The User's Original File Name

This sample builds on the code developed in the "Getting Started" chapter, in the example, "A Simple Upload in ASP.NET". It assumes that you already understand how to configure your application and that you know how to perform at least a simple upload.

In the "Simple Upload in ASP.NET" sample, the code is already set up to preserve the user's original file name. The user's original file name and path on the client is automatically sent by the browser when the form is uploaded. When FileUp parses the request, it is able to read in this information. If you choose to call the Save method on the file, FileUp preserves the original file name. The directory to which the file is saved will be retrieved from the path property setting.

excerpted from A Simple Upload in ASP.NET:
C# ...
//--- Get a reference to the uploaded file field
SaFile file = (SaFile)fileUpload.Form["myFile"];

//--- If the file does not exist, FileUp will
//--- throw an error when save() is called.
if (file != null)
{
if (!file.IsEmpty)
{
file.Save();
...
VB.NET ...
'--- Get a reference to the uploaded file field.
Dim file As SaFile = CType (fileUpload.Form ("myFile"), SaFile)

'--- If the file does not exist, FileUp will
'--- throw an error when save() is called.
If Not (file Is Nothing) Then
If Not (file.IsEmpty) Then
file.Save()
...

The Save method does not take any parameters. To set the upload's destination directory, you must set the Pathproperty.

Alternately, you can preserve the original file name if you call SaveAs() in conjunction with the ShortFileNameproperty. The ShortFileName property will return the original name of the file as it was named on the client.

C# | file.SaveAs("c:\\MyDirectory\\" + file.ShortFileName);
VB.NET | file.SaveAs("c:\MyDirectory\" & file.ShortFileName)

Taking the Lesson Further...
  • To discover the original name of the file before saving, use the ShortFileName property.

  • If you would like to verify the client-side path in addition to the original file name, use the UserFileName property instead.

  • If you are preserving the user's original file name, you may want to instruct FileUp how to handle situations where the uploaded file has the same name as a file that already exists in your upload directory. By default, FileUp will overwrite the existing file with the new file. You can change this behavior by using one of the following strategies:

    • Set FileUp's OverwriteFiles property to "False" so that an error can be raised.

    • Set FileUp's CreateNewFile property to "True" so that FileUp can automatically handle a situation of a pre-existing file by renaming the new file by appending an underscore and a number between 0 and 999 to the file's name.

Top


Adding a Second File

This sample builds on the code developed in the "Getting Started" chapter, in the example, "A Simple Upload in ASP.NET". It assumes that you already understand how to configure your application and that you know how to perform at least a simple upload.

FileUp can process an upload request that contains more than one file. To add an additional file, just add another <input type="file">tag to your form. You will need to add a file input control for each file that you want to upload.

Although the Internet standard specification for HTTP upload (RFC 1867 [image]) permits filenames with wildcards (for example, "*.doc"), neither Netscape nor Microsoft Internet Explorer support names with wildcards at this time. When they do, FileUpwill be able to process file names with wildcards uploaded from Netscape and IE. The client-side tool SoftArtisans XFile [image] supports uploading wildcards from the client.

Assuming that we are starting with the code available from the previous tutorial, A Simple Upload in ASP.NET, start by adding another file input element to the HTML form.

Edit your code from A Simple Upload in ASP.NETto include a second file input element.
<form id="theForm" runat="server" enctype="multipart/form-data" method="post">

Enter Filename:

<input type="file" id="myFile" name="myFile" />

<input type="file" id="myFile2" name="myFile2" />
Click "Browse" to select a file to upload.

<input type="button" id="UploadBtn" runat="server"
OnServerClick="UploadBtn_Click" value="Upload File" />

</form>

<asp:literal id="ltrUploadResults" runat="server" />

After the second file input element is added to the client HTML, you must prepare your server-side processing code to handle the second file. Code additions are below, in bold text.

C#
//--- Declare the FileUp object
FileUp fileUpload = null;

//--- This StringBuilder will be used to display results.
System.Text.StringBuilder results = new System.Text.StringBuilder();

try
{
//--- Instantiate the FileUp object
fileUpload = new FileUp (Context);

   //---Set the path property to the location where
//---you would like the file to be saved.
//---The path property takes a physical path,
//---but this sample will save
//---to the FileUp Samples "temp" directory.
//---The MapPath() function converts this relative path
//---to a physical path.
   fileUpload.Path = "C:\\temp";

   //--- Get a reference to the first uploaded file field
   SaFile file = (SaFile)fileUpload.Form["myFile"];

   //--- Get a reference to the second uploaded file field
   SaFile file2 = (SaFile)fileUpload.Form["myFile2"];

   //--- If the file does not exist, FileUp will
//--- throw an error when Save() is called.
   if (file != null)
{
if (!file.IsEmpty)
{
file.Save();

//--- Display information about the saved file.
results.Append("FileUp Saved the File Successfully.<br />");

         //--- The full sample code demonstrates many more properties
//--- that can be used to return information in the Response.
results.Append("<b>Path on server</b>" + file.ServerName);
}
}

   //--- If the file does not exist, FileUp will
//--- throw an error when Save() is called.
   if (file2 != null)
{
if (!file2.IsEmpty)
{
file2.Save();

//--- Display information about the saved file.
results.Append("FileUp Saved the File Successfully.<br />");

         //--- The full sample code demonstrates many more properties
//--- that can be used to return information in the Response.
results.Append("<b>Path on server</b>" + file2.ServerName);
}
}

//--- Display the results on the webform
ltrUploadResults.Text = results.ToString();
}
catch (Exception ex)
{
//--- If an exception is caught, display the details
ltrUploadResults.Text = "<b>An error has occurred:</b><br />" +
ex.Message;
}
finally
{
//--- Always call Dispose in the finally block
{    if(fileUpload != null)
fileUpload.Dispose();
fileUpload = null;
}
}
VB.NET
'--- Declare the FileUp object
Dim fileUpload As FileUp

'--- This StringBuilder will be used to display results.
Dim results As New System.Text.StringBuilder()

Try

'--- Instantiate the FileUp object
fileUpload = New FileUp (Context)

   '---Set the path property to the location where
'---you would like the file to be saved.
'---The path property takes a physical path,
'---but this sample will save
'---to the FileUp Samples "temp" directory.
'---The MapPath() function converts this
'---relative path to a physical path.
   fileUpload.Path = P"C:\temp"

   '--- Get a reference to the first uploaded file field.
Dim file As SaFile = CType (fileUpload.Form ("myFile"), SaFile)

   '--- Get a reference to the second uploaded file field.
Dim file2 As SaFile = CType (fileUpload.Form ("myFile2"), SaFile)

   '--- If the file does not exist, FileUp will
'--- throw an error when Save() is called.
   If Not (file Is Nothing) Then
If Not (file.IsEmpty) Then
file.Save()

         '--- Display information about the saved file
results.Append("FileUp Saved the File Successfully.<br />")

         '--- The full sample code demonstrates many more properties
'--- that can be used to return information in the Response.
results.Append("<b>Path on server</b>" + file.ServerName )
End If
End If

   '--- If the file does not exist, FileUp will
'--- throw an error when Save() is called.
   If Not (file2 Is Nothing) Then
If Not (file2.IsEmpty) Then
file2.Save()

         '--- Display information about the saved file
results.Append("FileUp Saved the File Successfully.<br />")

         '--- The full sample code demonstrates many more properties
'--- that can be used to return information in the Response.
results.Append("<b>Path on server</b>" + file2.ServerName )
End If
End If

   '--- Display the results on the webform
   ltrUploadResults.Text = results.ToString()

Catch ex As System.Exception

   '--- If an exception is caught, display the details
   ltrUploadResults.Text = "<b>An error has occurred:</b><br />" + _
ex.Message

Finally

   '--- Always call FileUp.Dispose in the finally block
   If Not (fileUpload Is Nothing) Then
fileUpload.Dispose()
fileUpload = Nothing
End If

End Try

In this case, we are referring to the file elements explicitly by name, and calling the Save method on each file. In the code sample above, you can see that the same lines of code are repeated for each file, but they simply refer to the other file object.

An alternative to explicit naming of each file object is to set up a loop to save all files that are submitted. This is useful not only for code maintenance issues, but it also allows you to set up a script that can handle an unknown number of files, such as may be the case when when you are using a client tool such as XFile. To see an example of this coding strategy, please see Accessing Multiple Form Elements.

Top


Accessing Multiple Form Elements

This tutorial builds on the concepts developed in the "Getting Started" chapter, in the example, "A Simple Upload in ASP.NET". It assumes that you already understand how to configure your application and that you know how to perform at least a simple upload.

In the previous examples a form was used that only contained file input elements. However, most people want to capture additional information on the form, such as a description, along with the file.

In ASP.NET, one would typically expect the use of server controls in addition to HTML controls. If you are using .NET server controls, you do not need to do anything out of the ordinary to access those controls. However, HTML controls, such as the file input control, should be accessed in a specific way.

HTML controls are typically accessed via Request.Form("name of element"). When uploading files, you it is recommended to change the encoding type of the form to "multipart/form-data".

FileUpprovides a Formobject for accessing the form elements. It provides identical functionality to Request.Form.

FileUp also provides the FormExobject, which handles collections of form elements (listboxes, radio buttons, multiple files, etc.).

The following code sample provides the HTML to create a form like the one in the picture above. All of the controls are HTML controls. The server-side code will demonstrate two approaches to handling multiple controls:

  1. Use Form or FormEx to gain named references to each control
  2. Develop a generic, resuable script that uses a loop to handle any number of controls, of any type, including files.

The Form
This code is based on the "Save All In Loop" upload sample that is set up in the FileUp samples installation directory
<form runat="server" id="theForm" enctype="multipart/form-data" method="post">
<table width="600" align="center" border="0">
<tr>
<td align="right" valign="top">Enter Filename:</td>
<td align="left"> <input type="file" id="myFile1" name="myFile1" /> </td>
</tr>
<tr>
<td align="right" valign="top">Enter Filename:</td>
<td align="left"> <input type="file" id="myFile2" name="myFile2" /> </td>
</tr>
<tr>
<td align="right" valign="top">Enter Filename:</td>
<td align="left"> <input type="file" id="myFile3" name="myFile3" /> <br />
<i>Click "Browse" to select a file to upload</i></td>
</tr>
<tr>
<td align="right">Textbox:</td>
<td> <input type="text" id="TextBox" name="TextBox"
value="Some text..." /> </td>
</tr>
<tr>
<td align="right">Password:</td>
<td> <input type="password" value="Shhh... password" id="PasswordBox"
name="PasswordBox" /> </td>
</tr>
<tr>
<td align="right">Radio:</td>
<td> <input type="radio" id="RadioBtn" name="RadioBtn" value="FileUp"
checked="checked" /> FileUp
<input type="radio" id="RadioBtn" name="RadioBtn" value="ExcelWriter" />
ExcelWriter</TD>
</tr>
<tr>
<td align="right">Checks:</td>
<td> <input type="checkbox" id="CheckBox" name="CheckBox" value="Red"
checked="checked" /> Red<br />
      <input type="checkbox" id="CheckBox" name="CheckBox" value="White"
checked="checked" />
White<br>
      <input type="checkbox" id="CheckBox" name="CheckBox" value="Blue"
checked="checked" />
Blue</TD>
</tr>
<tr>
<td align="right">DropDown:</td>
<td> <select id="DropDown" name="DropDown">
<option>Yes</option>
<option>No</option>
</select> </td>
</tr>
<tr>
<td align="right">MultiSelect:<br />
<i>(Hold Ctrl to multiselect)</i></td>
<td> <select id="MultiSelect" name="MultiSelect" size="3" multiple="multiple">
<option selected="selected">ASP</option>
<option>ASP.NET</option>
<option selected="selected">C#</option>
<option>VB.NET</option>
</select>
</tr>
<tr>
<td align="right"> </td>
<td align="left"> <input type="button" runat="server" id="UploadBtn"
OnServerClick="UploadBtn_Click" value="Upload File" /> </td>
</tr>
</table>
</form>
<asp:literal id="ltrUploadResults" runat="server" />
Accessing the Form Elements By Name

As demonstrated in previous examples, you can access file input elements by name via the FileUp Form object.

Accessing a file control by name, via the [FileUp].Form object:
C# | SaFile file1 = (SaFile)fileUpload.Form["myFile1"];
VB.NET | Dim file1 As SaFile = CType (fileUpload.Form ("myFile1"), SaFile)

The same can be done with other HTML controls, provided they can only provide on value, such as is the case for an input control of the type "text".

Accessing a single-value, non-File control by name, via the [FileUp].Form object:
C# String tbValue;
tbValue = fileUpload.Form["textbox"].ToString();
VB.NET Dim tbValue as String
tbValue = fileUpload.Form("textbox").ToString()

If a control can supply multiple values, such as a multi-select list box, then you will need to use the [FileUp].FormEx instead of [FileUp].Form. FormEx can also handle form elements that only contain one value, such as a file input element or a text box.

Accessing a single-value control by name, via the FormEx collection:
C# //--- A single-valued control's value will be found
//--- in the first item in its collection
//--- The index is 1-based
String tbValue;
SaMultiSelectCollection oFormExItem =
(SaMultiSelectCollection)fileUpload.FormEx["textbox"];
tbValue = oFormExItem[1].ToString();
VB.NET '--- A single-valued control's value will be found
'--- in the first item in its collection
'--- The index is 1-based

Dim tbValue as String
Dim oFormExItem As SaMultiSelectCollection = _
CType(fileUpload.FormEx("textbox"), SaMultiSelectCollection)
tbValue = oFormExItem(1).ToString()

Accessing a multiple-value control by name, via the FormEx collection:
C# System.Text.StringBuilder results = new System.Text.StringBuilder();
SaMultiSelectCollection oFormExItem =
SaMultiSelectCollection)fileUpload.FormEx["MultiSelect"];

if(oFormExItem.Count > 0)
{
foreach(object subitem in oFormExItem)
{
results.Append("<li>" + subitem.ToString() + "</li>");
}
}
VB.NET Dim results As New System.Text.StringBuilder()
Dim oFormExItem As SaMultiSelectCollection = _
CType(fileUpload.FormEx("MultiSelect"), SaMultiSelectCollection)
If (oFormExItem.Count > 0) Then
For Each subitem As Object In oFormExItem
results.Append("<li>" + subitem.ToString() + "</lt>")
Next subitem
End If
Processing All Elements in Loop

Another approach to accessing all of the form elements, regardless of number or type sumbitted, would be to loop through the FormEx collection. The following code sample can be used as your server-side processing script for the above form.

C#
private void ProcessUpload() {

//--- Declare an object for FileUp
FileUp fileUpload = null;

//--- This StringBuilder will be used to display results
System.Text.StringBuilder results = new System.Text.StringBuilder();

try
{

//--- Instantiate FileUp
fileUpload = new FileUp(Context);

//--- When the HttpModule is used, the path property does not
//--- affect caching location. Instead it is merely used
//--- as a placeholder to store the path to the directory
//--- where the files will be saved.
fileUpload.Path = "C:\\temp");

//--- Write the table header
results.Append("<div align="center"><h3>Upload Results</h3></div>");
results.Append("<table width="90%" align="center" border="1">");
results.Append("<th>Element type</th><th>Element Name</th><th>Value</th>");

//--- This main loop will iterate through every submitted form element
//--- Within the loop, we'll test it to see if it's a file or a text form
//--- element. If it's a text form element, we'll see if it's a single-value
//--- or a subcollection

foreach(object item in fileUpload.FormEx)
{

//--- ASP.NET submits several hidden fields
//--- with every PostBack for internal use such as
//--- __VIEWSTATE. Those hidden fields begin with
//--- a double-underscore. We'll ignore these.
if(item.ToString().StartsWith("__"))
continue;

//--- Get a reference for the current form element
//--- in the iteration
SaMultiSelectCollection oFormExItem =
(SaMultiSelectCollection)fileUpload.FormEx[item];

results.Append("<tr>");

//--- If there is more than one subitem in the current
//--- form element, it's a multiselect collection
//--- In this case, loop over the subitems
if(oFormExItem.Count > 1)
{
results.Append("<td>Subcollection</td><td>" +
item.ToString() + "</td><td>");

//--- Loop over the subitems of the current form element
foreach(object subitem in oFormExItem)
{
results.Append("<li>" + subitem.ToString() + "</li>");
}
results.Append("</td>");
}
//--- If there's only one item in the form element
//--- then it's not a multiselect collection
//--- We'll test to see if it's a file or a
//--- standard form element
else
{
//--- If it's a SaFile object, it's a file
if(oFormExItem[1] is SaFile)
{
SaFile file = (SaFile)oFormExItem[1];

//--- Check to be sure the file element isn't empty
if(!file.IsEmpty)
{
//--- It's not empty, so we'll save it
file.Save();
results.Append("<td>File</td><td>" + item.ToString() +
"</td><td>Saved as: " + file.ServerName + "</td>");
}
else
{
//--- It's empty, just write a message
results.Append("<td>File</td><td>" + item.ToString() + "</td>" +
"<td>(empty)</td>");
}
}
//--- If it's "string", it's just a standard
//--- form element
else if(oFormExItem[1] is string)
{
results.Append("<td>Form single value</td><td>" + item.ToString() +                "</td><td>" + oFormExItem[1].ToString() + "</td>");
}
}
results.Append("</dl>");
}

//--- Display the results on the webform
ltrUploadResults.Text = results.ToString();
}
catch(Exception ex)
{
//--- Show a message if an exception is caught
ltrUploadResults.Text = "<b>An exception has occurred</b><br />" +
ex.Message;
}
finally
{
//--- Always call Dispose in the finally block
if(fileUpload!=null)
{
fileUpload.Dispose();
fileUpload = null;
}
}
}
VB.NET
Private Sub ProcessUpload()

'--- Declare an object for FileUp
Dim fileUpload As FileUp

'--- This StringBuilder will be used to display results
Dim results As New System.Text.StringBuilder()

Try
'--- Instantiate the FileUp object
fileUpload = New FileUp(Context)

'--- When the HttpModule is used, the path property does not
'--- affect caching location. Instead it is merely used
'--- as a placeholder to store the path to the directory
'--- where the files will be saved.
fileUpload.Path = "C:\temp"

'--- Write the table header
results.Append("<div align="center"><h3>Upload Results</h3></div>")
results.Append("<table width="90%" align="center" border="1">")
results.Append("<th>Element type</th><th>Element Name</th><th>Value</th>")

'--- This main loop will iterate through every submitted form element
'--- Within the loop, we'll test it to see if it's a file or a text form
'--- element. If it's a text form element, we'll see if it's a single-value
'--- or a subcollection

For Each item As Object In fileUpload.FormEx

'--- ASP.NET submits several hidden fields
'--- with every PostBack for internal use such as
'--- __VIEWSTATE. Those hidden fields begin with
'--- a double-underscore. We'll ignore these.
If (item.ToString().StartsWith("__")) Then
'--- VB.NET lacks a "continue" keyword. This Goto
'--- command jumps to end very end of the loop
Goto EndItemLoop
End If

'--- Get a reference for the current form element
'--- in the iteration
Dim oFormExItem As SaMultiSelectCollection
oFormExItem = CType(fileUpload.FormEx(item), SaMultiSelectCollection)

results.Append("<tr>")

'--- If there is more than one subitem in the current
'--- form element, it's a multiselect collection
'--- In this case, loop over the subitems
If (oFormExItem.Count > 1) Then

results.Append("<td>Subcollection</td><td>" + _
item.ToString() + "</td><td>")

'--- Loop over the subitems of the current form element
For Each subitem As Object In oFormExItem
results.Append("<li>" + subitem.ToString() + "</li>")
Next subitem
results.Append("</td>")

'--- If there's only one item in the form element
'--- then it's not a multiselect collection
'--- We'll test to see if it's a file or a
'--- standard form element
Else

'--- If it's a SaFile object, it's a file
If (oFormExItem(1).GetType() Is GetType(SaFile)) Then

Dim file As SaFile = CType(oFormExItem(1), SaFile)

'--- Check to be sure the file element isn't empty
If Not (file.IsEmpty) Then

'--- It's not empty, so we'll save it
file.Save()
results.Append("<td>File</td><td>" + item.ToString() + _
"</td><td>Saved as: " + file.ServerName + "</td>")

Else

'--- It's empty, just write a message
results.Append("<td>File</td><td>" + item.ToString() + "</td>" + _
"<td>(empty)</td>")

End If

'--- If it's "string", it's just a standard
'--- form element
ElseIf(oFormExItem(1).GetType() Is GetType(String)) Then
results.Append("<td>Form single value</td><td>" + _
item.ToString() + "</td><td>" + _
End If
End If

results.Append("</dl>")

EndItemLoop:
Next item

'--- Display the results on the webform
ltrUploadResults.Text = results.ToString()

Catch ex As System.Exception
'--- Show a message if an exception is caught
ltrUploadResults.Text = "<b>An exception has occurred</b><br />" + _
ex.Message
Finally
'--- Always call FileUp.Dispose in the finally block
If Not (fileUpload Is Nothing) Then
fileUpload.Dispose()
fileUpload = Nothing
End If

End Try

End Sub

Summary

  • Because you are submitting files with the upload request, you should use:

    • <form enctype="multipart/form-data" ... >
    • Access the form elements through either FileUp.Form or FileUp.FormEx
  • FileUp.Form can be used for files or controls with only one value.
  • FileUp.FormEx must be used for controls that provide more than one value.
  • You can access the form elements by name, or make your code more extensible by accessing elements via a loop through all items in FileUp.Form or FileUp.FormEx.

Top


Limiting the Upload Size

FileUp provides two different means for limiting the size of files or uploads that are written to your webserver in the MaxBytes and MaxBytesToCancelsettings.

If you look through the documentation, you will notice that MaxBytesand MaxBytesToCancel exist both as properties and as registry keys. You should only set either the properties or the keys, but not both. Knowing when to set the properties versus the registry keys is dependent on whether or not you are using the HttpModule. Because the HttpModule caches the request before any ASP.NET code is executed, the HttpModule must be informed of these settings via the registry.

Environment | How to Set the Values
ASP | Set values as FileUp Properties
ASP.NET, using the HttpModule | Set values as Registry Keys
ASP.NET, without the HttpModule (not recommended) | Same as for ASP
MaxBytes: Limiting by Individual Files

The MaxBytes registry setting specifies the maximum number of bytes on a per file basis that the HttpModule will write to disk before passing on the request for further processing. This means that files will be truncated at the size specified in the MaxBytes setting. No errors will be raised by FileUp when this occurs. Setting this key to 0 disables MaxBytes, and this is the default value. When using ASP or ASP.NET without the HttpModule, use the MaxBytes property of the FileUp object. When using the HttpModule, you must use this registry setting instead, since the HttpModule processes the request before the ASP.NET script is executed.

MaxBytesToCancel: Cancelling the Request Based on its Size.

Specifies the maximum size in bytes of the entire Request before the HttpModule will abort the Request. Setting this key to 0 disables MaxBytesToCancel, and this is the default value. When using ASP or ASP.NET without the HttpModule, use the MaxBytesToCancel property of the FileUp object. When using the HttpModule, you must use this registry setting instead, since the HttpModule processes the request before the ASP.NET script is executed.

Making Size Limitations User-friendly

Both of these settings are stop-gap measures that can be employed to protect your webserver from certain types of attacks; however, used alone, they are not ideal for providing a user-friendly experience to legitimate users. The following suggestions might be employed to provide a better interaction with your end user:

  • Using TotalBytes with MaxBytes
    Since the MaxBytes setting may result in truncated files, you will need to devise a system for distiguishing between files that are exactly the size of the MaxBytes setting and those files that have been truncated. One possibility is to set MaxBytes to 1 byte higher than your actual cut-off point. The TotalBytes property of the File object can be used to test for any files that are the same size as your MaxBytes property. A message can be sent to the user that the file has been truncated, or the file can be deleted from the webserver with the Fileobject's delete method.
C#
//--- Get a reference to the uploaded file field
SaFile file = (SaFile)fileUpload.Form["myFile"];

if(file != null)
{
if(!file.IsEmpty)
{
// --- The MaxBytes registry key has been set to 1025
// --- even though the actual desired cut-off is 1024
// --- This will help us avoid confusion between properly
// --- sized files and those that have been truncated
// --- because of the MaxBytes setting.

UInt64 total;
total = file.TotalBytes;

if(total > 1024)
{
// --- Delete the file from the webserver, because it's
// --- too large and most likely was truncated by the
// --- MaxBytes setting anyway.
file.Delete();
}
else
{
file.Save();
}
}
}
VB.NET
'--- Get a reference to the uploaded file field
Dim file As SaFile = CType(fileUpload.Form("myFile"), SaFile)

If Not (file Is Nothing) Then
If Not (file.IsEmpty) Then

'--- The MaxBytes registry key has been set to 1025
'--- even though the actual desired cut-off is 1024
'--- This will help us avoid confusion between properly
'--- sized files and those that have been truncated
'--- because of the MaxBytes setting.

Dim noMathNumber as UInt64
noMathNumber = file.TotalBytes

Dim number as Int64
'--- We know MaxBytes is cutting off files at 1025 bytes
'--- so I'm not worried about an overflow error
number = System.Convert.ToInt64(noMathNumber)

If (number > 1024) then
'--- Delete the file from the webserver, because it's
'--- too large and most likely was truncated by the
'--- MaxBytes setting anyway.
file.Delete
Else
file.Save()
End If
End If
End If
  • Using an Intelligent Client
    An intelligent client such as SoftArtisans XFile can be used to test the size of the upload request or individual files beforethe request leaves the client. The user can be informed and instructed on how to correct the situation immediately, instead of waiting for a round-trip to the server and back.

Top


Restricting File Types

There are times when you may need to restrict the type of files saved on the Web server. One approach is to use the File object's ContentTypeproperty and a Select/Switch condition to save only files that are a certain type.

It is important to understand that FileUp populates the ContentType property from the Content-Type header in the upload request. This value is determined by the browser; therefore you will want to test for all possible variations in possible Content-Type values that could be submitted for the files you want to allow. The following example demonstrates the use of the ContentType property as a testing mechanism for choosing to call either the Save() or Delete() methods on a file.

Once your file is uploaded, you would include the following after creating an instance of FileUp:

C# String strContentType;
strContentType = file.ContentType;

switch(strContentType)
{
case "image/gif":
file.Save();
break;
case "image/pjpeg":
file.Save();
break;
default:
file.Delete();
break;
}
VB.NET Dim strContentType as String
strContentType = file.ContentType

Select Case strContentType
Case "image/gif"
file.Save
Case "image/pjpeg"
file.Save
Case Else
file.Delete
End Select

Alternately, you can test for file name extensions. In order to test for a file name extension beforea file is saved, you should pull the extension from the name of the file as it was on the client. Do this by using the ShortFileNameproperty.

Summary

  • To restrict a file by media type, identify the media content of an uploaded file using the ContentTypeproperty.

  • Alternately, to restrict a file by file name extension, identify a file's original name, without the original path, by using ShortFileNameand parsing for the extension.

  • To restrict the types of files to be uploaded before they leave the client, consider using an intelligent client such as SoftArtisans XFile. Please see Restricting File Size and Type Before Uploading.

Top


Adding a Server-Side Progress Indicator

This sample builds on the concepts taught in the "Getting Started" chapter, in the example, "A Simple Upload in ASP.NET". It assumes that you already understand how to configure your application and that you know how to perform at least a simple upload.

FileUp includes a server-side progress indicator that can be displayed to the user using HTML. The server-side progress indicator lets you know how much of the entire upload has arrived at the server. In an upload from the browser to an ASP.NET page, include the progress indicator in a separate page. In this page, you can get and display to the user:

  • The Percentage of the upload that has reached the server.
  • TotalBytes in the upload.
  • TransferredBytes so far.

You can use HTML techniques to customize the output effect, and display a counter or a progress bar.

Progress Indication in ASP.NET
Under ASP.NET, FileUp's progress indication is handled by the HttpModule. Therefore, to display accurate progress indication in ASP.NET, upload to a file with the .uplx extension.
Example

The complete code for the following example is available in the "Progress Indicator" sample included in the "FileUp/Samples/UploadSamples" installation directory. This sample contains the following pages:

Page Name | Function
ProgressUpload.uplx | Contains the display HTML for the form and will display the response. Also responsible for opening the progress indicator window.
ProgressUpload.uplx.[vb|cs] | Code-behind of ProgressUpload.uplx: Contains the logic that will accept the request on the server, save out the files and coordinate progress indication.
ProgressIndicator.aspx | Contains the display HTML for the progress indicator.
ProgressIndicator.aspx.[vb|cs] | Code-behind for ProgressIndicator.aspx: Instantiates the FileUp Progress Indicator object and provides logic for progress indication display.

There are 5 steps to this process:

  1. Obtain a ProgressID on the Server before rendering the HTML for the upload form.
  2. Provide the HTML form as usual, but attach a script to start progress on the "onsubmit" event of the form.
  3. Provide a graphical representation of progress with HTML.
  4. Provide the logic to drive the progress display in the code-behind[ProgressIndicator.aspx.[vb|cs] of the Progress Indicator page.
  5. Set up ProgressUpload.uplx.[vb|cs] to synchronize with the progress indicator before parsing the request.
Step One: Obtain a ProgressID on the Server before rendering the HTML for the upload form.

A Progress ID must be obtained from the FileUp Progress Indicator object as the first step to an upload request that will provide progress indication. This Progress ID will be used to synchronize the progress indication display code and the FileUp upload processing code, even though they exist in separate pages, on separate threads. This progress ID must be obtained from the Progress Indicator object's NextProgressId() function. It should not be "set" as a value in any other way (do not provide your own values). The progress indicator provides an identifier to distinguish a particular upload's progress indication from any other progress indication occuring in other upload requests being handled by FileUp on the same webserver.

In the code behind of ProgressUpload.uplx, instantiate the FileUp Progress object on the Page_Load event.

C# protected void Page_Load(object sender, EventArgs e)
{
   //--- When the page is first loaded, generate a new progress id
   if (!Page.IsPostBack)
   {
      //--- FileUpProgress.NextProgressId generates a new progress id
      FileUpProgress progress = new FileUpProgress();
      progressid = progress.NextProgressId();
   }
}
VB.NET Protected Sub Page_Load(sender As Object, e As EventArgs)

   '--- When the page is first loaded, generate a new progress id
   If Not (Page.IsPostBack) Then
      '--- FileUpProgress.NextProgressId generates a new progress id
      Dim progress As New FileUpProgress()
      progressid = progress.NextProgressId()
   End If

End Sub
Step Two: Provide the HTML form as usual, but attach a script to start progress on the "onsubmit" event of the form.

This HTML form is identical to the form used in the Simple Upload in ASP.NET example, except that we will attach a function to the "onsubmit" event of the form. This function will open a new window for the progress indicator, passing it the Progress ID in the querystring. Likewise, the action attribute of the HTML form will be updated to include the Progress ID in its querystring.

The HTML Form (in ProgressUpload.uplx)
<html>
<head>
<title>SoftArtisans FileUp ASP.NET Progress Indicator Sample</title>

<script language="javascript">
/*
This small function makes sure that the progress indicator and server-side
processing page receive the new progress ID we just created in the CodeBehind class.
Also, it pops up the progress window.
*/
function startUpload()
{
   winStyle = "height=200,width=550,status=no,scrollbars=no,toolbar=no,"       "menubar=no,location=no";
   if(theForm.myFile.value != "")
      window.open("ProgressIndicator.aspx?progressid=<%=progressid%>", "_blank", winStyle);
   theForm.action = theForm.action + "?progressid=" + <%=progressid%>;
}
</script>
</head>
<body>
<form onSubmit="startUpload();" id="theForm" runat="server"
   enctype="multipart/form-data" method="post">
   Enter Filename: <input type="file" id="myFile" name="myFile" />
   Click "Browse" to select a file to upload
   <input runat="server" OnServerClick="UploadBtn_Click" id="UploadBtn"
      type="submit" value="Upload File" />
   <asp:literal id="ltrUploadResults" runat="server" />
</form>
</body>
</html>

Adding a Server-Side Progress Indicator

This sample builds on the concepts taught in the "Getting Started" chapter, in the example, "A Simple Upload in ASP.NET". It assumes that you already understand how to configure your application and that you know how to perform at least a simple upload.

FileUp includes a server-side progress indicator that can be displayed to the user using HTML. The server-side progress indicator lets you know how much of the entire upload has arrived at the server. In an upload from the browser to an ASP.NET page, include the progress indicator in a separate page. In this page, you can get and display to the user:

  • The Percentage of the upload that has reached the server.
  • TotalBytes in the upload.
  • TransferredBytes so far.

You can use HTML techniques to customize the output effect, and display a counter or a progress bar.

Progress Indication in ASP.NET
Under ASP.NET, FileUp's progress indication is handled by the HttpModule. Therefore, to display accurate progress indication in ASP.NET, upload to a file with the .uplx extension.
Example

The complete code for the following example is available in the "Progress Indicator" sample included in the "FileUp/Samples/UploadSamples" installation directory. This sample contains the following pages:

Page Name | Function
ProgressUpload.uplx | Contains the display HTML for the form and will display the response. Also responsible for opening the progress indicator window.
ProgressUpload.uplx.[vb|cs] | Code-behind of ProgressUpload.uplx: Contains the logic that will accept the request on the server, save out the files and coordinate progress indication.
ProgressIndicator.aspx | Contains the display HTML for the progress indicator.
ProgressIndicator.aspx.[vb|cs] | Code-behind for ProgressIndicator.aspx: Instantiates the FileUp Progress Indicator object and provides logic for progress indication display.

There are 5 steps to this process:

  1. Obtain a ProgressID on the Server before rendering the HTML for the upload form.
  2. Provide the HTML form as usual, but attach a script to start progress on the "onsubmit" event of the form.
  3. Provide a graphical representation of progress with HTML.
  4. Provide the logic to drive the progress display in the code-behind[ProgressIndicator.aspx.[vb|cs] of the Progress Indicator page.
  5. Set up ProgressUpload.uplx.[vb|cs] to synchronize with the progress indicator before parsing the request.
Step One: Obtain a ProgressID on the Server before rendering the HTML for the upload form.

A Progress ID must be obtained from the FileUp Progress Indicator object as the first step to an upload request that will provide progress indication. This Progress ID will be used to synchronize the progress indication display code and the FileUp upload processing code, even though they exist in separate pages, on separate threads. This progress ID must be obtained from the Progress Indicator object's NextProgressId() function. It should not be "set" as a value in any other way (do not provide your own values). The progress indicator provides an identifier to distinguish a particular upload's progress indication from any other progress indication occuring in other upload requests being handled by FileUp on the same webserver.

In the code behind of ProgressUpload.uplx, instantiate the FileUp Progress object on the Page_Load event.

C# protected void Page_Load(object sender, EventArgs e)
{
   //--- When the page is first loaded, generate a new progress id
   if (!Page.IsPostBack)
   {
      //--- FileUpProgress.NextProgressId generates a new progress id
      FileUpProgress progress = new FileUpProgress();
      progressid = progress.NextProgressId();
   }
}
VB.NET Protected Sub Page_Load(sender As Object, e As EventArgs)

   '--- When the page is first loaded, generate a new progress id
   If Not (Page.IsPostBack) Then
      '--- FileUpProgress.NextProgressId generates a new progress id
      Dim progress As New FileUpProgress()
      progressid = progress.NextProgressId()
   End If

End Sub

Step Two: Provide the HTML form as usual, but attach a script to start progress on the "onsubmit" event of the form.

This HTML form is identical to the form used in the Simple Upload in ASP.NET example, except that we will attach a function to the "onsubmit" event of the form. This function will open a new window for the progress indicator, passing it the Progress ID in the querystring. Likewise, the action attribute of the HTML form will be updated to include the Progress ID in its querystring.

The HTML Form (in ProgressUpload.uplx)
<html>
<head>
<title>SoftArtisans FileUp ASP.NET Progress Indicator Sample</title>

<script language="javascript">
/*
This small function makes sure that the progress indicator and server-side
processing page receive the new progress ID we just created in the CodeBehind class.
Also, it pops up the progress window.
*/
function startUpload()
{
   winStyle = "height=200,width=550,status=no,scrollbars=no,toolbar=no," &
      "menubar=no,location=no";
   if(theForm.myFile.value != "")
      window.open("ProgressIndicator.aspx?progressid=<%=progressid%>", "_blank", winStyle);
   theForm.action = theForm.action + "?progressid=" + <%=progressid%>;
}
</script>
</head>
<body>
<form onSubmit="startUpload();" id="theForm" runat="server"
   enctype="multipart/form-data" method="post">
   Enter Filename: <input type="file" id="myFile" name="myFile" />
   Click "Browse" to select a file to upload
   <input runat="server" OnServerClick="UploadBtn_Click" id="UploadBtn"
      type="submit" value="Upload File" />
   <asp:literal id="ltrUploadResults" runat="server" />
</form>
</body>
</html>

Step Three: Provide a graphical representation of progress with HTML

The FileUp Progress Indicator does not provide it's own GUI. Instead, it provides information on progress indication so that you can develop your own custom represenatation of progress. In this sample, we are using an HTML table and an <hr> element to function as a progress meter.

ProgressIndicator.aspx
<html>
<body>
<h3>Upload Progress:</h3>
<!--
This table holds cells that are used to display
the upload progress for the progress indicator
-->
<asp:Table id="UploadTable"
   GridLines="Both"
   HorizontalAlign="Center"
   Font-Name="Verdana"
   Font-Size="8pt"
   CellPadding="15"
   CellSpacing="0"
   runat="server"<

   <asp:tablerow>
      <asp:tablecell><b>Progress ID</b></asp:tablecell>
      <asp:tablecell width="300"><b>Graphic</b></asp:tablecell>
      <asp:tablecell><b>Transferred Bytes</b></asp:tablecell>
      <asp:tablecell><b>Total Bytes</b></asp:tablecell>
      <asp:tablecell><b>Percentage</b></asp:tablecell>
   </asp:tablerow>
   <asp:tablerow>
      <asp:tablecell runat="server" id="cellProgressID" text="0" />
      <asp:tablecell runat="server" id="cellGraphic">
         <HR align="left" style="color:blue" size="10" width="<%=strPercent%>" />
      </asp:tablecell>
      <asp:tablecell runat="server" id="cellTransferredBytes" />
      <asp:tablecell runat="server" id="cellTotalBytes" />
      <asp:tablecell runat="server" id="cellPercentage" />
   </asp:tablerow>
</asp:table>
</body>
</html>

Step Four: Provide the logic to drive the progress display in the code-behind ProgressIndicator.aspx.[vb|cs] of the Progress Indicator page.

Here you will instantiate the FileUp Progress Indicator object and retrieve the ProgressID from the querystring. Once the ID has been assigned to the Progress Indicator object, the Percentage property is checked. The page will continue to refresh, updating the display graphics until it reaches 100%.

C#
public class ProgressIndicator : System.Web.UI.Page
{
   //--- Declare a string and controls used on the webform
   //--- to display the upload progress
   protected string strPercent = String.Empty;
   protected System.Web.UI.WebControls.TableCell cellProgressID;
   protected System.Web.UI.WebControls.TableCell cellTransferredBytes;
   protected System.Web.UI.WebControls.TableCell cellTotalBytes;
   protected System.Web.UI.WebControls.TableCell cellPercentage;

   protected void Page_Load()
   {
      //--- Each time the page is loaded, update the upload progress
      UpdateProgress();
   }

   private void UpdateProgress()
   {
      //--- Delare an object for the FileUp progress object
      FileUpProgress progress = null;

      try
      {
         //--- Instantiate the FileUpProgress object
         progress = new FileUpProgress();

         //--- Get the Progress ID from the query string
         int intProgressId = Convert.ToInt32(Request.QueryString["progressid"]);

         //--- Important: Assign the progress ID to the object to monitor
         //--- the upload
         progress.ProgressId = intProgressId;

         //--- If the upload isn't complete, continue to refresh the page
         //--- to display the progress
         if(progress.Percentage < 100)
            Page.Response.Write("<meta http-equiv=\"Refresh\" content="1" />");

         //--- Update the progress table below with the current information
         cellProgressID.Text = progress.ProgressId.ToString();
         strPercent = progress.Percentage.ToString("N") + "%";
         cellTransferredBytes.Text = progress.TransferredBytes.ToString();
         cellTotalBytes.Text = progress.TotalBytes.ToString();
         cellPercentage.Text = progress.Percentage.ToString("N");
      }
      catch (Exception ex)
      {
         cellProgressID.Text = "<b>An exception has occurred</b><br>" +
            ex.Message;
      }
      finally
      {
         //--- Always call Dispose in the finally block
         if (progress != null)
      {
         progress.Dispose();
         progress = null;
      }
   }
}
VB.NET
Public Class ProgressIndicator : Inherits System.Web.UI.Page

   '--- Declare a string and controls used on the webform
   '--- to display the upload progress
   Protected strPercent As String = String.Empty
   Protected cellProgressID As System.Web.UI.WebControls.TableCell
   Protected cellTransferredBytes As System.Web.UI.WebControls.TableCell
   Protected cellTotalBytes As System.Web.UI.WebControls.TableCell
   Protected cellPercentage As System.Web.UI.WebControls.TableCell

   Protected Sub Page_Load(sender As Object, e As EventArgs)
      '--- Each time the page is loaded, update the upload progress
      UpdateProgress()
   End Sub

   Private Sub UpdateProgress()

      Dim progress As FileUpProgress
      Try

         '--- Instantiate the FileUpProgress object
         progress = New FileUpProgress()

         '--- Get the Progress ID from the query string
         Dim intProgressId As Integer
         intProgressId = Convert.ToInt32(Request.QueryString("progressid"))

         '--- Important: Assign the progress ID to the object to monitor
         '--- the upload
         progress.ProgressId = intProgressId

         '--- If the upload isn't complete, continue to refresh the page
         '--- to display the progress
         If progress.Percentage < 100 Then
            Page.Response.Write("<meta http-equiv=""Refresh"" content="1" />")
         End If

         '--- Update the progress table below with the current information
         cellProgressID.Text = progress.ProgressId.ToString()
         strPercent = progress.Percentage.ToString("N") + "%"
         cellTransferredBytes.Text = progress.TransferredBytes.ToString()
         cellTotalBytes.Text = progress.TotalBytes.ToString()
         cellPercentage.Text = progress.Percentage.ToString("N")
      Catch ex As System.Exception
         cellProgressID.Text = "<b>An exception has occurred</b><br>" + _
            ex.Message
      Finally
         If Not (progress Is Nothing) Then
            progress.Dispose()
            progress = Nothing
         End If
       End Try
   End Sub

End Class

Top

Copyright © 2010 SoftArtisans, Inc. All rights reserved.

Step Three: Provide a graphical representation of progress with HTML

The FileUp Progress Indicator does not provide it's own GUI. Instead, it provides information on progress indication so that you can develop your own custom represenatation of progress. In this sample, we are using an HTML table and an <hr> element to function as a progress meter.

ProgressIndicator.aspx
<html>
<body>
<h3>Upload Progress:</h3>
<!--
This table holds cells that are used to display
the upload progress for the progress indicator
-->
<asp:Table id="UploadTable"
   GridLines="Both"
   HorizontalAlign="Center"
   Font-Name="Verdana"
   Font-Size="8pt"
   CellPadding="15"
   CellSpacing="0"
   runat="server"<

   <asp:tablerow>
      <asp:tablecell><b>Progress ID</b></asp:tablecell>
      <asp:tablecell width="300"><b>Graphic</b></asp:tablecell>
      <asp:tablecell><b>Transferred Bytes</b></asp:tablecell>
      <asp:tablecell><b>Total Bytes</b></asp:tablecell>
      <asp:tablecell><b>Percentage</b></asp:tablecell>
   </asp:tablerow>
   <asp:tablerow>
      <asp:tablecell runat="server" id="cellProgressID" text="0" />
      <asp:tablecell runat="server" id="cellGraphic">
         <HR align="left" style="color:blue" size="10" width="<%=strPercent%>" />
      </asp:tablecell>
      <asp:tablecell runat="server" id="cellTransferredBytes" />
      <asp:tablecell runat="server" id="cellTotalBytes" />
      <asp:tablecell runat="server" id="cellPercentage" />
   </asp:tablerow>
</asp:table>
</body>
</html>

Step Four: Provide the logic to drive the progress display in the code-behind ProgressIndicator.aspx.[vb|cs] of the Progress Indicator page.

Here you will instantiate the FileUp Progress Indicator object and retrieve the ProgressID from the querystring. Once the ID has been assigned to the Progress Indicator object, the Percentage property is checked. The page will continue to refresh, updating the display graphics until it reaches 100%.

C#
public class ProgressIndicator : System.Web.UI.Page
{
   //--- Declare a string and controls used on the webform
   //--- to display the upload progress
   protected string strPercent = String.Empty;
   protected System.Web.UI.WebControls.TableCell cellProgressID;
   protected System.Web.UI.WebControls.TableCell cellTransferredBytes;
   protected System.Web.UI.WebControls.TableCell cellTotalBytes;
   protected System.Web.UI.WebControls.TableCell cellPercentage;

   protected void Page_Load()
   {
      //--- Each time the page is loaded, update the upload progress
      UpdateProgress();
   }

   private void UpdateProgress()
   {
      //--- Delare an object for the FileUp progress object
      FileUpProgress progress = null;

      try
      {
         //--- Instantiate the FileUpProgress object
         progress = new FileUpProgress();

         //--- Get the Progress ID from the query string
         int intProgressId = Convert.ToInt32(Request.QueryString["progressid"]);

         //--- Important: Assign the progress ID to the object to monitor
         //--- the upload
         progress.ProgressId = intProgressId;

         //--- If the upload isn't complete, continue to refresh the page
         //--- to display the progress
         if(progress.Percentage < 100)
            Page.Response.Write("<meta http-equiv=\"Refresh\" content="1" />");

         //--- Update the progress table below with the current information
         cellProgressID.Text = progress.ProgressId.ToString();
         strPercent = progress.Percentage.ToString("N") + "%";
         cellTransferredBytes.Text = progress.TransferredBytes.ToString();
         cellTotalBytes.Text = progress.TotalBytes.ToString();
         cellPercentage.Text = progress.Percentage.ToString("N");
      }
      catch (Exception ex)
      {
         cellProgressID.Text = "<b>An exception has occurred</b><br>" +
            ex.Message;
      }
      finally
      {
         //--- Always call Dispose in the finally block
         if (progress != null)
      {
         progress.Dispose();
         progress = null;
      }
   }
}
VB.NET
Public Class ProgressIndicator : Inherits System.Web.UI.Page

   '--- Declare a string and controls used on the webform
   '--- to display the upload progress
   Protected strPercent As String = String.Empty
   Protected cellProgressID As System.Web.UI.WebControls.TableCell
   Protected cellTransferredBytes As System.Web.UI.WebControls.TableCell
   Protected cellTotalBytes As System.Web.UI.WebControls.TableCell
   Protected cellPercentage As System.Web.UI.WebControls.TableCell

   Protected Sub Page_Load(sender As Object, e As EventArgs)
      '--- Each time the page is loaded, update the upload progress
      UpdateProgress()
   End Sub

   Private Sub UpdateProgress()

      Dim progress As FileUpProgress
      Try

         '--- Instantiate the FileUpProgress object
         progress = New FileUpProgress()

         '--- Get the Progress ID from the query string
         Dim intProgressId As Integer
         intProgressId = Convert.ToInt32(Request.QueryString("progressid"))

         '--- Important: Assign the progress ID to the object to monitor
         '--- the upload
         progress.ProgressId = intProgressId

         '--- If the upload isn't complete, continue to refresh the page
         '--- to display the progress
         If progress.Percentage < 100 Then
            Page.Response.Write("<meta http-equiv=""Refresh"" content="1" />")
         End If

         '--- Update the progress table below with the current information
         cellProgressID.Text = progress.ProgressId.ToString()
         strPercent = progress.Percentage.ToString("N") + "%"
         cellTransferredBytes.Text = progress.TransferredBytes.ToString()
         cellTotalBytes.Text = progress.TotalBytes.ToString()
         cellPercentage.Text = progress.Percentage.ToString("N")
      Catch ex As System.Exception
         cellProgressID.Text = "<b>An exception has occurred</b><br>" + _
            ex.Message
      Finally
         If Not (progress Is Nothing) Then
            progress.Dispose()
            progress = Nothing
         End If
       End Try
   End Sub

End Class
Step Five: Set up ProgressUpload.uplx.[vb|cs] to synchronize with the progress indicator before parsing the request.

The upload request processing code must first be preceeded by code that synchronizes progress indication by instantiating the Progress Indicator object and passing it the ProgressID for this upload. After this synchronization, the rest of the upload processing code is written as usual.

C#
protected void UploadBtn_Click(object sender, EventArgs e)
{
   //--- Hide the form after the upload button is clicked
   theForm.Visible = false;
   ProcessUpload();
}

//--- Process the upload request
private void ProcessUpload()
{
   //--- Declare an object for FileUp
   FileUp fileUpload = null;

   //--- Decalre an object for the file
   SaFile file = null;

   try
   {
      //--- Instantiate the FileUp object
      fileUpload = new FileUp(Context);

      //--- Get the progress id from the querystring
      int intProgressID = Convert.ToInt32(Request.QueryString["progressid"]);
      fileUpload.ProgressID = intProgressID;

      //--- This StringBuilder will be used to display the results of the upload
      System.Text.StringBuilder results = new System.Text.StringBuilder();

      fileUpload.Path = "C:\\Temp"

      //--- Check to be sure there was a file selected in the form
      //--- If so, continue processing

      //--- Get a reference to the uploaded file field
      file = (SaFile)fileUpload.Form["myFile"];

      if (file != null)
      {
         if (!file.IsEmpty)
         {

            file.Save();

            //--- Display information about the saved file
            results.Append("<h3>FileUp Saved the File Successfully</h3>");
            //--- More results code can be placed here (see full sample)

         }
         else
         {
            //--- If SaFile.IsEmpty is true, the file field was left empty
            results.Append("There was no file submitted in the form field.");
         }
      }
      else
      {
         results.Append("The referenced field does not exist or is not " &
            "of type=\"file\"");
      }

      //--- Display the results on the webform
      ltrUploadResults.Text = results.ToString();
   }
   catch (Exception ex)
   {
      //--- If an exception is caught, display the results
      ltrUploadResults.Text = "<b>An error has occurred:</b><br />" +
         ex.Message;
   }
   finally
   {
      //--- Always call Dispose in the finally block
      if (fileUpload != null)
   {
      fileUpload.Dispose();
      fileUpload = null;
   }
}
VB.NET
Protected Sub UploadBtn_Click(sender As Object, e As EventArgs)

   '--- Hide the form after the upload button is clicked
   theForm.Visible = False
   ProcessUpload()

End Sub

'--- Process the upload request
Private Sub ProcessUpload()

   '--- Declare an object for FileUp
   Dim fileUpload As FileUp

   '--- Declare an object for the file
   Dim file As SaFile

   Try

      '--- Instantiate the FileUp object
      fileUpload = New FileUp(Context)

      '--- Get the progress id from the querystring
      Dim intProgressID As Integer = _
         Convert.ToInt32(Request.QueryString("progressid"))
      fileUpload.ProgressID = intProgressID

      '--- This StringBuilder will be used to display the results of the upload
      Dim results As New System.Text.StringBuilder()

      fileUpload.Path = "C:\temp"

      '--- Check to be sure there was a file selected in the form
      '--- If so, continue processing

      '--- Get a reference to the uploaded file field
      file = CType(fileUpload.Form("myFile"), SaFile)

      If Not (file Is Nothing) Then
         If Not (file.IsEmpty) Then

            file.Save()

            '--- Display information about the saved file
            results.Append("<h3>FileUp Saved the File Successfully</h3>")
            '---- More results code can be placed here (see full sample code)

         Else
            '--- If SaFile.IsEmpty is true, the file field was left empty
            results.Append("There was no file submitted in the form field.")
         End If
      Else
         results.Append("The referenced field does not exist or is not " + _
            "of type=""file""")
      End If

      '--- Display the results on the webform
      ltrUploadResults.Text = results.ToString()

   Catch ex As System.Exception
      '--- If an exception is caught, display the results
      ltrUploadResults.Text = "<b>An error has occurred:</b><br />" + _
         ex.Message
   Finally
      '--- Always call FileUp.Dispose in the finally block
      If Not (fileUpload Is Nothing) Then
         fileUpload.Dispose()
         fileUpload = Nothing
      End If
   End Try

End Sub

Top


Using FileUp with ADO.NET

FileUp fully supports the ADO.NET DataReader and DataTable objects. You can pass ADO.NET data types to FileUp's SaveAsBloband TransferBlobmethods. Note that you can still use ADO with FileUp in ASP.NET.

  • ADO.NET and TransferBlob
  • ADO.NET and SaveAsBlob
  • Chunked Inserts and Updates in ADO.NET

ASP.NET Samples
FileUp includes many sample ASP.NET applications in both C# and VB.NET. To run the samples, open a browser window and enter the URL http://localhost/safileupsamples. The sample code is in the folder FileUp\Samples.
ADO.NET and TransferBlob

FileUp's TransferBlob method downloads a file from a database. Using ADO.NET, a reference to the database BLOB that contains the file can pass the file to TransferBlob:

  • As an array of bytes, or
  • Using the DataReader object

Using DataReader requires less memory and is almost always faster than using a byte array. In the following example, the file to download from the database is assigned to a DataReader object and the DataReader object is passed to TransferBlob.

C#
<%@ Page Language="C#" %>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.Data.OleDb" %>
<%@ Import namespace="SoftArtisans.Net" %>

...

//--- Create the FileUp object
FileUp fileUpload = new FileUp(Context);

//--- Open an ADO.NET OleDbConnection
OleDbParameter param = new OleDbParameter();
OleDbConnection conn = new OleDbConnection(Application["connString"].ToString());
conn.Open();

//--- Set a new OleDbCommand object to query the database.
OleDbCommand cmdReadBinary = new OleDbCommand("SELECT FileBinary " &
" FROM UploadTable WHERE ID=1", conn);

//--- Use the DataReader object to get the query result (the
//--- file to download).
OleDbDataReader dr;
dr = cmdReadBinary.ExecuteReader(CommandBehavior.SequentialAccess);

...

//--- Pass the DataReader object to the TransferBlob method
//--- and download the file.
fileUpload.TransferBlob(dr, 0, 256);

...

Top

ADO.NET and SaveAsBlob

FileUp's SaveAsBlob method saves an uploaded file in a database. SaveAsBlob can write the uploaded file to an ADO.NET DataColumn, as demonstrated in the following example.

VB.NET
<%@ Page Language="VB"% >
<%@ Import namespace="SoftArtisans.Net" %>
<%@ Import namespace="System.Data.OleDb" %>
<%@ Import namespace="System.Data" %>

'--- Create an instance of FileUp.
Dim fileUpload As FileUp = New FileUp(Context)

...

'--- Set a new DataAdapter object to query the database.
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT FileName, " + _
"FileBinary FROM UploadTable", conn)

...

'--- Create a new DataSet and execute the SELECT statement
'--- to fill the DataSet with data.
Dim ds As DataSet = New DataSet()
da.MissingSchemaAction = MissingSchemaAction.AddWithKey
da.Fill(ds, "UploadTable")

'--- Create a new row in the DataSet.
Dim row As DataRow
row = ds.Tables("UploadTable").NewRow()

'--- Insert the file name and file into fields in the new row.
row(0) = fileUpload.ShortFilename
row(1) = fileUpload.SaveAsBlob()

'--- Update the DataSet
ds.Tables("UploadTable").Rows.Add(row)
da.Update(ds, "UploadTable")
conn.Close()

...

Top

Chunked Inserts and Updates in ADO.NET

FileUp supports chunked database inserts and updates with ADO.NET in SQL Server. This is done using SQL Server's UPDATETEXT command and FileUp's SaveAsBlob override method to write chunks of data to a BLOB column.

If UseMemoryis set to True, you cannot use SaveAsBlob to chunk uploaded data to the database.

Use the following SaveAsBlob syntax when creating a chunked update:

SaveAsBlob(SqlCommand SqlCmd, SqlParameter inParam, SqlParameter outParam)

SaveAsBlob is a method of both the FileUpobject and the Fileobject. If FileUp.SaveAsBlob is called in an upload of more than one file, the first file will be saved.

The following example shows you how to use the new SaveAsBlob method.

With UPDATETEXT the BLOB column - the column to which the file is uploaded - must not be null. Therefore, a single byte is written to the column. FileUp deletes the byte when the file is inserted.

C#
<%@ Page Language=C# debug=true trace=false %>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.Data.OleDb" %>
<%@ Import namespace="System.Data.SqlClient" %>
<%@ Import Namespace="SoftArtisans.Net" %>
<script runat=server>

int Insert(SqlConnection cn)
{
// "SELECT @@IDENTITY;" is necessary only if you are retrieving an identity
// column value
String strSql = "INSERT INTO Categories(CategoryName, Description, Picture) " &
VALUES(@CategoryName, @Description, @Picture);SELECT @@IDENTITY;";

SqlCommand cmd = new SqlCommand(strSql, cn);

SqlParameter categoryNameParam =
cmd.Parameters.Add("@CategoryName", SqlDbType.NChar, 15);
SqlParameter descriptionParam =
cmd.Parameters.Add("@Description", SqlDbType.NText, 16);
SqlParameter pictureParam =
cmd.Parameters.Add("@Picture", SqlDbType.Binary, 16);

categoryNameParam.Value = "TestFile";
descriptionParam.Value = "My Test Image";

// The BLOB column (to which the file is uploaded) must not be null,
// so insert one byte. FileUp will delete this byte when the file is inserted.
pictureParam.Value = new System.Byte[1];

int identity= 0;
SqlDataReader reader= cmd.ExecuteReader(CommandBehavior.SequentialAccess);

// Retrieve the identity column value for the new row. This value
// will be used to open the new row.
reader.Read();
identity = (int)reader.GetDecimal(0);
reader.Close();

return nIdentity;
}

void Page_Load(object sender, EventArgs args)
{
try
{
FileUp fileUpload = new FileUp(Context);
SqlConnection cn = new SqlConnection("Data Source=localhost;" &
"Persist Security Info=False;User ID=sa;" &
"Initial Catalog=Northwind;");
cn.Open();
int identity= 0;

// Insert a new row into the database.
identity= Insert(cn);

String strSql = "SET NOCOUNT ON;UPDATE Categories SET Picture = 0x0 " &
"WHERE CategoryName='Seafood';SELECT @Pointer=TEXTPTR(Picture) " &
"FROM Categories WHERE CategoryID=@CategoryID";

SqlCommand cmdGetPointer = new SqlCommand(strSql, cn);
SqlParameter categoryIDParam =
cmdGetPointer.Parameters.Add("@CategoryID", SqlDbType.Int);
categoryIDParam.Value = nIdentity;

SqlParameter outParam =
cmdGetPointer.Parameters.Add("@Pointer", SqlDbType.VarBinary, 100);
outParam.Direction = ParameterDirection.Output;

// Open the row with the 'UPDATE' sql command and get a 'TEXTPTR'
// pointer to the blob column.
int nRows = cmdGetPointer.ExecuteNonQuery();

// Verify that the row was opened.
if(outParam.Value == System.DBNull.Value)
{
Response.Write("Failed to open row");
cn.Close();
return;
}

// Create an System.Data.SqlClient.SqlCommand reference using the
// 'UPDATETEXT' sql command, creating 'Pointer', 'Offset', and 'Delete'
// parameters so that FileUp can properly chunk data to the database column.
SqlCommand sqlCmd = new SqlCommand("UPDATETEXT Categories.Picture " &
"@Pointer @Offset @Delete WITH LOG @Bytes", cn);
SqlParameter inParam =
sqlCmd.Parameters.Add("@Pointer", SqlDbType.Binary, 16);

//call SaveAsBlob
fileUpload.SaveAsBlob(sqlCmd, inParam, outParam);

//Close the database connection.
cn.Close();
}
catch(Exception e)
{
Response.Write(e.ToString());
}
}
</script>

Top


Transactional Processing

  • Transactional Uploads
  • How To Upload With a Transaction (ASP)
  • How To Upload With a Transaction (ASP.NET)
  • Uploading to a Database Transaction


Transactional Uploads

Transactional Uploads offer the following important advantages:

  • Guaranteed synchronization between upload processing and database transactions.
  • Full COM+ integration.
  • Vastly simplified error handling and guaranteed integrity when uploading multiple files.
Guaranteed Synchronization with Database Transactions

Most upload applications log the upload into a database. Typically, an upload is processed and a file is written to the web server's hard disk. After an upload is complete, a database insert is performed to log the uploaded file. However, what happens if the database operation fails, due to a validation error for example? The uploaded file is left orphaned on the disk, with no corresponding database entry.

FileUpsolves this problem by automatically synchronizing the upload processing with the database transaction. If the database transaction rolls back, the upload is rolled back automatically as well, so no orphaned files are left on disk.

Similarly, if the upload fails for any reason, such as permissions problems or because of insufficient disk space, the database transaction is aborted. Your uploaded files and database entries are always synchronized.

This synchronization is available only with databases that provide transaction support via COM+, such as Microsoft SQL Server or Oracle.

Full COM+ Integration

SoftArtisans FileUpprovides a complete COM+ Resource Manager for uploading. The database synchronization described above works with any COM+ object. This means that if other COM+ objects in your application, synchronization is still guaranteed, even if no database operations participate in the COM+ transaction.

Simplified Error Handling and Guaranteed Integrity when Uploading Multiple Files

When using a database, it is very easy to combine a sequence of steps into a transaction. The programmer can be sure that all the steps will either execute successfully, or roll back to the pre-transaction state. For example:

   BeginTransaction
Insert Row
Update Other Row
CommitTransaction

Traditional ASP code for uploading does not allow this. Every action must be verified, such as:

fileUpload.FormEx("file1").Save
If Err <> 0 Then
Response.Write("Upload failed")
Else
fileUpload.Form("file2").Save
If Err <> 0 Then
...

This leads to code that is either difficult to read, or has incomplete or incorrect error checking. FileUp's transactional upload capability simplifies the problem significantly, as all file upload operations will complete successfully or roll back to the pre-transaction state. This ensures that when a user uploads multiple files, all of the uploaded files are written to the web server's hard disk, or no files are written at all. Best of all, the resulting code is very easy to read, yet has complete error handling.

<%@ language="vbscript" TRANSACTION="Required" %>

<%
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")
fileUpload.Path = "d:\uploads"
fileUpload.Form("file1").Save
fileUpload.Form("file2").Save

' The Transacted Script Abort Handler. This sub-routine
' will be called if the script transacted aborts

Sub OnTransactionAbort()
Response.Write "<p><b>The Transaction has aborted</b>."
Response.Write "No uploaded files were saved."
End Sub
%>

Top


How to Upload with a Transaction (ASP)

How to Upload with a Transaction

You can control the upload transaction using COM+. If the transaction aborts, the file or files are deleted and the process is rolled back. Transactions are logged within the Transaction Statistics section of COM+. To view Transaction Statistics:

  1. From the Start menu, open Settings\Control Panel\Administrative Tools\Component Services.

  2. Open Component Services\Computers\My Computer\Distributed Transaction Coordinator\Transaction Statistics

To use FileUptransactionally, you must have FileUpinstalled as in COM+ a package. During FileUp's automatic installation process, you can choose to install FileUp in COM+. To find out whether a FileUp package is installed in COM+:

  1. From the Start menu, open Settings\Control Panel\Administrative Tools\Component Services.

  2. Open Component Services\Computers\My Computer\COM+ Applications.

  3. Under COM+ Applications, look for a FileUp package.

If FileUpis not installed in COM+ double-click the file SAFILETXInstall.vbs that is included in FileUp's installation directory.

How to Enable Transactional Processing in an ASP Page

In the FileUp upload processing script, to enable transactional processing, include the following line at the top of the page:

<%@ language="vbscript" TRANSACTION="Required" %>

Throughout your script, you can apply error handling with ObjectContext.SetAbort, to control the transaction. For example:

<%
If fileUpload.IsEmpty = 1 Then
'---Abort upload if file is empty.
ObjectContext.SetAbort %>

To display whether the transaction was committed or aborted, you can use the following subroutines:

<%
'--- Message appended to page if upload is a failure.
Sub OnTransactionAbort
Response.Write("<br /><hr><font color='red'> "+ _
"<b>Transaction has been aborted.</b></font>")
End Sub

'--- Message appended to page if upload is successful
Sub OnTransactionCommit
Response.Write("<br /><hr><font color='Green'>"+ _
"<HR>Transaction has been committed.</b></font>")
End Sub
%>


How to Upload with a Transaction (ASP.NET)

Transactional Upload in ASP.NET

Components do not need to be installed in COM+ to use COM+ services under .NET. If the type supports COM+ services, they are available automatically.

Using a Transaction in an ASP.NET page
  1. Add a Transaction page directive:
    <%@ Page Language=C# Transaction="Required"%>

  2. Optional - import the System.EnterpriseServices namespace:
    <%@ Import Namespace="System.EnterpriseServices" %>

  3. Abort or commit the transaction through the ContextUtil type (it is in the System.EnterpriseServices namespace):
    ContextUtil.SetAbort()

  4. Transaction events (OnTransactionAbort and OnTransactionCommit)
        are available in ASP.NET pages that use transactions:
void OnTransactionAbort()
{
Response.Write("<br><hr><font color='red'>")
Response.Write("<b>Transaction has been aborted.</b></font>");
}
void OnTransactionCommit()
{
Response.Write("<br><hr><font color='Green'>")
Response.Write("<hr>Transaction has been committed.</b></font>");
}

Top


Uploading to a Database Transaction

This sample show you how to create a transactional upload to a database. If anyaction does not take place, all actions will go back to their original state. This example uses the upload.mdb that is in the Samples directory.

First let's look at the form section for the first page. With this form you submit two text boxes and a file. The file will be exported into the database.

<form enctype="multipart/form-data" method="post"
action="TransDBFormResp.asp">

<table width="100%">
<tr>
<td align="right" valign="top">Author</td>
<td><input type="text" id="Author" name="Author" /></td>
</tr>
<tr>
<td align="right" valign="top">Description</td>
<td><input type="text" id="Descrip" name="Descrip" /></td>
</tr>
<tr>
<td align="right" valign="top">Enter Filename:</td>
<%
'---
'--- Note the use of the type="file" specification
'---
%>
<td align="left">
<input type="file" id="File1" name="File1" /><br />
<b><i><small>Note: if a button labeled "Browse..."
does not appear, then your browser does not support             File Upload. For Internet Explorer 3.02 users,
a free add-on is available from Microsoft.
Please see the FileUp documentation for more information.
</small></i></b></td>
</tr>
<tr>
<td align="right"> </TD>
<td align="left">
<input type="submit" id="Sub1" name="Sub1" value="Submit">
</td>
</tr>
</table>
</form>

Next let's look at the response page. It contains the instance of FileUpand the ADO recordset that adds the file and data into the database. We also set this page to be transactional.

On this page, you indicate that you will be using COM+ by including the following at the top of the page:

<%@ language="vbscript" TRANSACTION="Required" %>

Throughout the script, you can apply error handle with "ObjectContext.SetAbort", to control transaction.

Here is the code of the first major section:

<%
'---
'--- Create an instance of FileUp
'---
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")
'---
'--- Set the default path to store uploaded files. This step is not
'--- strictly necessary, but performance is better if you specify it.
'---
fileUpload.Path = "c:\temp"
%>
<% If Not IsObject(fileUpload.Form("File1")) Then %>
The form contains a tag named "File1" which is not of type="file".
Please check your form definition.
<% ElseIf fileUpload.Form("File1").IsEmpty = 1 Then
'---Abort of upload if file is empty
ObjectContext.SetAbort
%>
<%
'---
'--- Even if the filename field is empty, all of the
'--- other form elements are available.
'---
%>

In this section, we:

  • Create an instance of Fileup.
  • Establish the Path property.
  • Check that the File1 element is of the type "file".
  • Check to see if this element is empty.

In the last part, we call SetAbort to abort the transaction, since the file element is blank.

Further down the page we implement another condition:

<%
ElseIf fileUpload.Form("File1").ContentDisposition <> "form-data" Then
'---Abort upload if there ContentDisposition is incorrect
ObjectContext.SetAbort
%>
Your upload did not succeed, most likely because your browser
does not support Upload via this mechanism.

This condition tests the form to see if it supports the protocol for file transfer that FileUpuses. Once again we call SetAbort to abort the transaction if this condition is true.

The next section deals with another condition to verify whether one or both of the textboxes are blank. If so, the transaction is aborted:

<%
Else
If fileUpload.Form("Author") = "" _
Or fileUpload.Form("Descrip") = "" Then

'---Abort upload if there ContentDisposition is incorrect
ObjectContext.SetAbort
End If
%>

We then create an ADO recordset and establish error handling of the database interaction:

<%
On Error Resume Next
Set rsBlob = Server.CreateObject("ADODB.RecordSet")

'--- Open RecordSets
rsBlob.Open "IntermediateBlobTable", "AccessUpload", 2, 3

'---
'--- For SQL Server Users, use the following line to open
'--- the recordset. Make sure you replace:
'--- <myserver> by your SQL Server name
'---
'--- rsBlob.Open "IntermediateBlobTable", + _
'---   "driver={SQL Server};server=<myserver>" + _
'---   "uid=sa;pwd=;database=SQLServerUpload", 2, 3

'--- Add new record and update
rsBlob.AddNew
rsBlob.Fields("author") = fileUpload.Form("Author")
rsBlob.Fields("descrip") = fileUpload.Form("Descrip")
fileUpload.Form("File1").SaveAsBlob rsBlob.Fields("filecol")

rsBlob.Update
rsBlob.Close
Set rsBlob = Nothing

If Err <> 0 Then
'--- Abort upload if there are any errors
ObjectContext.SetAbort
%>
....
<%
End If
End If
%>

If any errors occur due to the database interaction, the entire process is rolled back. Otherwise, the transfer takes place.

At the very end of this page, we can display a message or perform an action based on the events of the transaction:

<%
'--- Message appended to page if upload is a failure
Sub OnTransactionAbort
Response.Write("<br /><hr /><font color="red"> " + _
"<b>Transaction has been aborted.</b></font>")
End Sub %>

<%
'--- Message appended to page if upload is successful
Sub OnTransactionCommit
Response.Write("<br /><hr /><font color="Green"> " +_
"<hr />Transaction has been committed.</b></font>")
End Sub
%>

As you can see, adding transactional properties to your upload is easy.

This completes the Transactional Processing tutorial. You can also try the Common Client-Side Solutions tutorial.

Top


Common Client-Side Solutions

Many times you may find that what you wish to accomplish with your uploads or downloads cannot be done with a purely server-side solution. The nature of the Internet requires a component to operate on the client's machine to achieve some functionality.

Users often have trouble solving problems because the browsers don't support viable solutions.

To address these needs that we offer a client-side tool, SoftArtisans XFile [image]. Xfile is included with FileUp Professional Edition (FileUpPE) or can be purchased separately.

Situation | Corresponding Example
Limit the files you upload to a specific type. You can restrict the types of files after they are uploaded, as demonstrated in the FileUp Restrict File Types example. But restricting file types before they leave the client is an excellent way to conserve bandwidth and server resources. Additionally, error handling can be provided to the user before a trip to the server is made, allowing corrections to be made in the least amount of time.
Restricting Files Before Uploading
Upload files in a directory tree while preserving its subdirectories and contents. | Directory Upload
Download multiple files in what appears to the end user to be just one action. | Simultaneous Downloading of Multiple Files
Provide client-side progress indication for both uploads and downloads. | Adding a Progress Indicator
Automate downloading. | Presetting Files for Download
Automatate uploading. | Automated Uploads Information

Top

SoftArtisans XFile
XFileis an ActiveX control that works within Internet Explorer, Visual Basic Programs, and even through a Windows shell extension. XFileis an excellent client-side solution for those who know that all their clients will be using Internet Explorer. Developers have a number of solutions when using XFile,including creating instances of the object through code, or using the AXFFile control which provides a graphical user interface. It can also be used from Active Server Pages, Internet Explorer, Visual Basic, and C++.

XFileis available on Win32 platforms, including Windows95, Windows98, Windows NT, Windows 2000, Windows XP and Windows 2003.

Top

For the following groups of examples to work properly, you need to have XFile installed on your system. If you are interested in an evaluation version, navigate to the SoftArtisans download page.

Top

Examples

The following examples demonstrate client-side solutions, using both XFile:

Restricting Files Before Uploading

Directory Upload

Browser Neutral Upload

Simultaneous Downloading of Multiple Files

Adding a Progress Indicator

Presetting Files for Download

Automating an Upload

The examples do not contain complete code. You will find many complete applications, including error handling, in FileUp's Samples directory.

Top


Restricting Files Before Uploading

Restricting File Type and Size Before Uploading

These examples shows how to restrict file types and set a maximum file size to upload. We'll use XFile instead of restricting at the server with FileUp. By restricting the file types on the client, the inappropriate files will not be uploaded at all. This saves from unneccesary bandwidth usage.

We'll need to parse through the filenames for the correct file extension.

Using XFile

Let's look at the first page:

The Client Code
<html>
<head>
<title>SoftArtisan XFile Restrict File Size and Type Upload Sample</title>
</head>

<body>
<strong>
<font color="black" size="5">
XFile File restrict Size and Type Upload Sample
</font>
</strong>

<object classid="CLSID:230C3D02-DA27-11D2-8612-00A0C93EEA3C"
id="AXFFile" name="AXFFile" style="left: 0px; top: 0px"
codebase="saxfile.cab" viewastext>
</object>

<input type="button" value="Button"
id="Button2" name="Button2" value="Start upload" />

<script language="vbs">

'-- This is where all the data will be sent
PostURL = "/SAfileUpSamples/ClientUpload/restrictTypeSize/SAXfile/formresp2.asp"

Set XFile = AXFFile.XFRequest
XFile.Server = "localhost"
XFile.ObjectName = PostURL
XFile.MaxFileSize = 500

AXFFile.AddFile "c:\boot.ini"
AXFFile.AddFile "C:\folder\file.jpg"

Sub Button2_onclick()
'-- Establish File Collection
'-- The files will upload but will not show up in the progress bar
Set files = AXFFile.Files

Dim ext(2)
ext(0) = "ini"
ext(1) = "txt"
ext(2) = "doc"

Dim fileDele
For Each p In files
For Each x In ext
fExt = Mid(p.FileName, InStrRev(p.FileName, ".") + 1)
fileDele = p.FileName
If StrComp(fExt, x) <> 0 Then
restCount = restCount + 1
End if
Next

If restCount = 3 Then ' number of extensions to restrict to
MsgBox(fileDele & " will be removed from the file list" & vbcrlf _
& "since it is not the correct file type")
AXFFile.Remove (p.FileName)
End If
restCount = 0
next

Call StartUpload

End Sub

Sub StartUpload()
winStyle = "height=300,width=400,status=no," & _
"toolbar=no,menubar=no,location=no"
Window.Open "AXFFileProgress.htm", "_blank", winStyle
AXFFile.Start()
End Sub

</script>
</body>
</html>

Let's look at the major sections of interest:

  • First we create the AXFFile object from the XFile cab.

    <object classid="CLSID:230C3D02-DA27-11D2-8612-00A0C93EEA3C" id="AXFFile"
    name="AXFFile" style="LEFT: 0px; TOP: 0px"
    codebase="saxfile.cab" viewastext>
    </object>

  • We create a button that will be used for firing a subroutine for the restricting of file types and calling the upload function - StartUpload()

    <input type="button" value="Button" id="Button2" name="Button2" value="Start upload" />

  • Now we are establishing the properties that set up the XFile transfer. We call an instance of the Request object and then set the Server. With ObjectName property, we set the web page that will create the upload process. The MaxFileSize property is where we set the max size to be uploaded. The error for the max size is intrinsic to the component. We have set this to 500 bytes.

    <script language="vbscript">

    Set XFile = AXFFile.XFRequest
    XFile.Server = "localhost"
    XFile.ObjectName = PostURL
    XFile.MaxFileSize = 500

  • This is where we preset files to be uploaded.

       AXFFile.AddFile "C:\boot.ini"
    AXFFile.AddFile "C:\folder\softartlogo.jpg"

  • This is the onclick event subroutine. This is where we create the file collection and restrict the type by the extension. We first create an instance of the file collection with the Files object. Then an array is created with all of the file type extensions to which we want to restrict the upload. The FileDele variable is set to the filename that will be deleted. There are two iterations that are used for the extension array and the file collection. Within the second iteration we get the extension of the file from the list. We set the variable, FileDele to the file in the list and then compare the file extension and the extension from the array created. If the comparison is not equal to 0, which mean they are the same, then we add a count of the extension (RestCount variable) not matched. This will iterate until all the extensions from the array are verified. If the count is equal to the amount of extension matched, then the file is not one of the file types specified and it is removed from the list. Each time the ResCount is set back to zero to reset the process. We then go to the next file in the collection until there is no more. After which the StartUpload subroutine is called.

    Sub Button2_OnClick()
    '--- Establish File Collection
    '--- The files will upload but will not show up in the progress bar
    Set files = AXFFile.Files

    'MsgBox("File count: " & files.Count)
    Dim ext(2)
    ext(0) = "ini"
    ext(1) = "txt"
    ext(2) = "doc"

    Dim fileDele
    For Each p In files
    For Each x In Ext
    fExt = Mid(p.FileName, InStrRev(p.FileName, ".") + 1)
    fileDele = p.FileName
    If StrComp(fExt, x) <> 0 Then
    restCount = restCount + 1
    End If
    Next
    If restCount = 3 Then ' number of extensions to restrict to
    MsgBox(fileDele & " will be removed from the file list" & vbCrLf _
    & "since it is not the correct file type")
    AXFFile.Remove (p.FileName)
    End If
    restCount = 0
    Next

    Call StartUpload

    End Sub

  • The startUpload subroutine sets the progress window that will be opened through the transfer, and then transfer begins.

    Sub StartUpload()
    winStyle = "height=300,width=400,status=no,toolbar=no,menubar=no,location=no"
    Window.Open "AXFFileProgress.htm", "_blank", winStyle
    AXFFile.Start()
    End Sub
    </script>

    Top


Directory Upload

Directory Upload: Using XFile

FileUpcan process an upload of a full directory and its subdirectories. This can be done using FileUpin combination with SoftArtisans XFile.

Scripting a Recursive Upload with SoftArtisans XFile

The Server-Side Script

Scripting a Recursive Upload with SoftArtisans XFile

Use the XFRequest object's method,AddDirectoryRecursive to upload a directory. For example:

The Client Code
<script language="vbscript">

Sub UploadButton_OnClick()

'-- Set the URL where we want to send the data by
'-- using the CurrentURL property
XFRequest.CurrentURL =
"http://localhost/SAFileUpSamples/Recursive/Xfile/" & _
"ResurXfileResp.asp"

'--- Add Directory and subdirectory with all files
XFRequest.AddDirectoryRecursive("C:\temp\download")

' -- Start the transfer
XFRequest.Start
End Sub

</script>

Top

The Server-Side Script

In the upload processing script on the server, use FileUp's SaveRecursive()method instead of Save or SaveAs.

The following code shows what your response page looks like:

<%
'--- Create an instance of FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

fileUpload.Path = "D:\Uploads"

'--- Save full directory of files
fileUpload.SaveRecursive()
%>

If you plan to display the properties of the uploaded file when the transfer is complete, code your page as if you were uploading multiple files. For example:

<table width="95%" border="1" cellspacing="2"
cellpadding="0" height="206">
<tr>
<th colspan="2"><p align="center">Contents of The Form</p></th>
</tr>
<tr>
<th width="20%"><p align="center"><center>Tag Name</p></th>
<th width="80%"><p align="center"><center>Value</p></th>
</tr>
<%
For Each item In fileUpload.Form
Response.Write("<tr><td align=""right"">" & _
item & "</td>")
If Not IsObject(fileUpload.Form(item)) Then
'--- This is a regular (non-file) form element. Show its value
Response.write("<td>" & fileUpload.Form(item) & "</td></tr>")
Else
'--- This is a form element. Show all the details
%>
<td>
<table width="100%" border="1" cellspacing="2"
cellpadding="0" height="206">
<tr>
<th colspan="2"><p align="center">File Details</p></th>
</tr>
<tr>
<th width="35%"><p align="center"><center>Item</p></th>
<th width="65%"><p align="center"><center>Value</p></th>
</tr>
<tr>
<td width="35%" align="right" valign="top">
Server filename</td>
<td width="65%"><%=fileUpload.Form(item).ServerName%> </td>
</tr>
<tr>
<td width="35%" align="right" valign="top"> User's filename</td>
<td width="65%"><%=fileUpload.Form(item).UserFilename%>
</td>
</tr>
</table></td>
</tr>
<%
End If
Next
%>

For more examples, check out the samples provided as part of the FileUpdistribution. See Programmer's Samples for a list of the contents of the Samples directory.

Top


Simultaneous Downloading of Multiple Files

At some point, you may need to download multiple files at the same time. This example shows how to download multiple files simultaneously using XFile.

Multi-file Download with SoftArtisans XFile

This example illustrates using XFile'sVisual (GUI) control. You'll find this useful in getting around browsers' usual limitation of downloading one file at a time.

For this example, we need two HTML files (SAXFileMultiDown.htm and AXFFileProgress.htm) and one ASP file (FormResp.asp). The first HTML file will contain our ActiveX control user interface, with which the user selects one or all the files to be downloaded. The other one allows us to view the progress of the download. The ASP file, named FormResp.asp, is where FileUp will take the request for the download and transfer the files from the server to the browser.

<%@ language="vbscript" %>

<html>
<head>
<title>Software Artisans SA-AXFile Download Sample</title>
<%
'--- Server name
httpHost = "localhost"

'--- Files to be downloaded
file1 = Server.URLEncode("boot.ini")
file2 = Server.URLEncode("config.sys")

%>
</head>
<body>
<p><strong><font color="black" size="5">SA-AXFile Download
Sample</font></strong></p>
<p></p>
<script language="javascript">

function startDownload() {
winStyle="Height=300,Width=400,Status=No,Toolbar=To,_       Menubar=No,Location=No";
window.open("AXFFileProgress.htm", "_blank", winStyle);
}

</script>

<object classid="CLSID:B82FA17C-F3A9-11D2-B5DD-0050041B7FF6"
id="AXFFileDownload" name="AXFFileDownload"
style="height: 200px; left: 0px; top: 0px; width: 400px"
viewastext>
</object>

<p><input id="Button1" name="Button1" type="button"
value="Start Download" onclick="startDownload()" /></p>

<script language="vbs">
Set XFile = AXFFileDownload.XFRequest

XFile.Server = <%=httpHost%>

AXFFileDownload.AddFile "C:\temp\boot.ini", _
"http://localhost/SAFileUpSamples/ClientDownload/MultiDownload" & _
"/FormResp.asp?" & "File=<%=File1%>"

AXFFileDownload.AddFile "C:\temp\config.sys", _
"http://localhost/SAFileUpSamples/ClientDownload/MultiDownload" & _
"/FormResp.asp?" & "File=<%=File2%>"

</script>

</body>
</html>

That's obviously a lot of information to take in at once so we'll cover the code one section at a time:

  • At the top of the page, we are establishing the local ASP variables that will be passed further into the code.
    • We use "localhost" to supply the name of the web server. This information is passed to the HttpHost variable.
    • Two more variables pass the file names to be downloaded. File1 equals "boot.ini" and File2 equals "config.sys". You will notice that we are using Server.URLEncode to change the text into URL syntax, otherwise the file names may not pass through correctly.

  • The StartDownload function opens the download process window. We are creating an instance of a window that will open "AXFFileProgress.htm". Inside this page is where the process actually starts. This will be explained when we discuss this page.

  • The next section includes the object tag, which will place the AXFFileDownload ActiveX control on the form. The ID is necessary to refer to the object later on in the code, while the other arguments, such as Appearance, BackColor, and ForeColor determine the appearance of the control.

  • The input tag creates a button whose OnClick event fires the StartDownload function we created above.

  • The last section sets some of the parameters of the AXFFileDownload control:

    • We create an object called XFile, which refers to AXFFileDownload's XFRequest object.

    • Using our new XFile object, we set the Server property of the XFRequest object. In this example, we use the localhost alias for the current machine. This is supplied by the HttpHost variable. In a real application, you could use a remote server's name.

    • The next section sets the files to be downloaded. Note that the first argument refers to the location where the file will be saved on the user's PC. The second argument refers to the URL of the response page and a querystring variable that ultimately tells FileUpwhich file to download.

AXFFileProgress.htm is a much simpler file, but the most important. This page starts the download process. We are calling the XFile'sProgress object, in order to display the status of the transfer. We ensure that the progress control is displayed before the transfer starts. Otherwise, in the multi-threaded environment of Internet Explorer, a transfer could complete before the progress window is displayed, yielding an inconsistent user experience.

<html>
<head>
<title>Software Artisans SA-AXFile Download Progress</title>

<script language="javascript">
function callback()
{
document.getElementById("AXFFileProgress").XFRequestStream =
opener.document.getElementById("AXFFileDownload").XFRequestStream;
document.getElementById("AXFFileProgress").ShowProgress();
opener.document.getElementById("AXFFileDownload").Start();
window.close();
}

</script>
</head>
<body onload="callback();">
<object id="AXFFileProgress"
classid="CLSID:C3EAF164-E06A-11D2-B5C9-0050041B7FF6"></object>
</body>
</html>

The sections of this file work as follows:

  • The callback function sets the XFRequestStream property so that the progress control can synchronize with the AXFFileDownload control. The Callback function also calls the Start function of the AXFFileDownload control so that the process may begin. The Progress window is then closed when the transaction is done.

  • The body tag includes the onload parameter, which calls the callback function as the Progress form is opened.

  • The object tag creates the AXFFileProgress control to be used on the page.

The last page deals with the download via the server. This is where FileUp is used to direct where the source file is on the server. This has very little code, but you can imagine adding more sophisticated functions for authorizations, logging, and management of the download.

There is the major section:

<%

'--- Get the QueryString value to be used as the source file to be downloaded.
file = Request.QueryString("File")

'---
'--- Create an instance of the file download component
'---
Set download = Server.CreateObject("SoftArtisans.FileUp")

'--- The root path would be supplied for the source of the download.
'--- In this example it is hard coded.
download.TransferFile "C:\" & File

%>

FileUp requires only a single parameter: the full path of the file to be transferred to the server. In this example, both files are in the same folder. You could also use the Querystring to specify an ID or some other means of making the server filename hidden.
    Here is an explanation of the code:
  • The QueryString variable, File, is passing into a local variable with the same name.
  • An instance of FileUp is created.
  • The TransferFile method is used with the definition of the source directory and the File variable, which contains the file to download.
If the download is complete, you will see checkmark over files inside of the interface. You could also use the transfer complete method within the AXFFileProgress.htm for additional user interaction.

Top


Adding a Progress Indicator

  • FileUp's Server-Side Progress Indicator
  • XFile's Client-Side Progress Indicator
FileUp's Server-Side Progress Indicator

FileUp includes a server-side progress indicator, that can be displayed to the user using HTML. The server-side progress indicator lets you know how much of the entire upload has arrived at the server. In an upload from the browser to an ASP page, include the progress indicator in a separate ASP page. In this page, you can get and display to the user:

  • The Percentage of the upload that has reached the server.
  • TotalBytes in the upload.
  • TransferredBytesso far.

You can use HTML techniques to customize the output effect, and display a counter or a progress bar.

The FileUp Progress Indicator is explained in-depth in the Programmer's Guide. Please see the page "Adding a Server-Side Progress Indicator appropriate to your development language.

Top

XFile's Client-Side Progress Indicator

SoftArtisans XFile provides a progress indicator that can show accurate client-side progress.

In this example, there are three objects involved:

AXFFile | The explorer-like file selection control that includes all the objects that are part of XFile.
XFRequest | The non-visual object that actually performs the transfer.
AXFFileProgress | The control that displays the progress of the transfer.

The Progress control displays the status of the transfer. We ensure that the Progress control is displayed before the transfer starts. Otherwise, in the multi-threaded environment of Internet Explorer, a transfer could complete before the progress window is displayed, yielding an inconsistent user experience.

Let's discuss how to create a progress window using XFile.

You need two HTML files for these examples: a page that contains AXFFile and a progress page.

The following code is an example of the page containing AXFFile:

The Client Code
<html>
<head> <script language="javascript">

XFile = AXFFile.XFrequest;
XFile.CurrentUrl = "localhost/safileupsamples/formresp2.asp";
AXFFile.AddFile("C:\boot.ini");
AXFFile.AddFile("C:\autoexec.bat");
function startUpload()
{
winStyle = "height=300,width=400,status=no," & _
"toolbar=no,menubar=no,location=no";
window.open("AXFFileProgress.htm", "_blank", winStyle);
}

</script>
</head> <body>
<strong>
<font color="black" size="5">
SoftArtisans Visual Control (AXFFile) Multi-File Preset Upload Sample
</font>
</strong>

<object classid="CLSID:230C3D02-DA27-11D2-8612-00A0C93EEA3C"
id="AXFFile" style="left: 0px; top: 0px">
</object>

<input id="Button1" name="Button1" type="button" value="Start Upload"
onclick = "startUpload()">

</body>
</html>

This is very similar to our multiple file download example . The StartUpload function is called from the button created later on in the script. Note that in this example, since we are using the graphical control , there is a different ClassID for the object.

The last script section should also look rather familiar. The major difference in this case is that the AddFile method only requires one argument; the location and naming of the files to be uploaded are handled by FormResp2.asp.

AXFFileProgress.htm starts the upload process. We instantiate the XFile Progress object AXFFileProgress to create and display properties of the transfer.

Here is the major section of AXFFileProgress.htm.

The Progress Indicator
.....
<head>
<script language="vbscript">
function callback()
{    Document.All("AXFFileProgress").XFRequestStream =       Opener.Document.All("AXFFile").XFRequestStream;
Document.All("AXFFileProgress").ShowProgress();
Opener.Document.All("AXFFile").Start();
Window.Close();
} function AXFFileProgress_TransferComplete()
{    alert("Transfer completed");
} </script>
</head>
<body onload="callback()">

<object id="AXFFileProgress"
classid="CLSID:C3EAF164-E06A-11D2-B5C9-0050041B7FF6">
</object>

The sections of this file work as follows:

  • The Callback function sets the XFRequestStream property of the AXFFileProgress control to that of the AXFFile control, and tells the progress control to show the upload progress. This is where the communication is made between the AXFFileProgress control and the AXFFile control. The Callback function also calls the Start function of the AXFFile control so that the process may begin. The Progress window is closed when the transfer is done.

  • The body tag includes the OnLoad parameter, which calls the Callback function as the Progress form is opened.

  • The object tag creates the AXFFileProgress control to be used on the page.

  • We then use the TransferComplete event handler to prompt when the upload is done.

Top

Top


Presetting Files for Upload

You may at times run into situations where you do not want the user to be able to set which files he or she will be uploading. For obvious reasons, this is not allowed with a purely server-based applications, as the security implications would be rather daunting. However, you can preset files with a client-side component.

Presetting Files with SoftArtisans XFile

For this example, you only need to create one file to post to the standard FormResp.asp.

Paste the following code into a standard HTML file:

The Client Code
<html>
<body>

<script language="vbscript">

Sub UploadButton_OnClick()
XFRequest.CurrentURL = "http://localhost/saxfilesamples/formresp2.asp"
XFRequest.AddFile "C:\Boot.ini", "FileName1"
XFRequest.Start
ResponseText.InnerHTML = XFRequest.Response
Document.GetElementById("UploadButton").Disabled = True
End Sub

</script>

<div align="center">
<h2>IE Based XFile Form Data and Multi-File "Post" Sample</h2>
<br />
To upload the preset files click the "Upload!" button.
<br />

<input type="button" id="UploadButton" name="UploadButton" value="Upload!" />

</div>
<span id="ResponseText"></span>

<object classid="ClSID:C3A57B60-C117-11D2-BD9B-00105A0A7E89"
codebase="saxfile.cab" id="XFRequest">
</object>

</body>
</html>

The code for this is fairly easy to understand. The object tag at the end creates an instance of XFile's XFRequest object.The codebase parameter is necessary for those users who have not yet installed XFile.This will obviously not be a real problem if you are just running the sample on a local machine, but it is essential to use this parameter if you are using XFilein a production environment. The ID parameter, which is set to "XFRequest", is necessary to allow us to refer to the object in the rest of our code.

We named the button in this example 'UploadButton'. Its sole purpose is to provide us with an "on click" event from which the script can be called.

Let's go through the sub procedure line by line:

  • The CurrentURL line sets the URL to where we want to send the data.
  • The AddFile line adds a file to be uploaded from the user's hard drive.
  • The Start line begins the upload process. Since we are only uploading one small file here, this process will not take long.
  • The ResponseText.InnerHTML line allows us to place the response from FormResp.asp into the area that we define with the SPAN tag later on. This allows us to see the results of the upload. If you do not want the user to see the results, it is not necessary to use this.
  • We disable the UploadButton by setting its Disabled property to True.

At this point, you should be able to open the HTML file, press the button, and have the boot.ini from your hard drive uploaded without having selected it manually.

For more examples, check out the samples provided as part of the FileUpdistribution. See Programmer's Samples for a list of the contents of the Samples directory.


Automating Uploads

Automating An Upload

There may be times when you do not want any user intervention to upload files. For example, if you upload the same files everyday, you may not need to see or select the filenames.

Using SoftArtisans XFile you can completely automate the upload.

Note: When a component is signed by SoftArtisans, there will always be a final conformation displayed to the user when automatically uploading. We provide XFile in an unsigned format so that you can apply your own digital signature.

When you sign the component, there will not be any confirmation of the upload by the user. You will have the ability to disable any prompt or display of the upload.

SoftArtisans, Inc. disavows all responsibility of XFileused in malicious ways to take files from a user's hard disk or to place files on a user's hard disk without their consent. By signing the control with your signature, you assume full responsibility that the control is used in an appropriate manner that respects the user's privacy and integrity.

Top

Automating An Upload with XFile

XFile does not need or have parameters to hide the control, since it depends on whether you are using the non-visual or visual object, which is determined by the Classid attribute of the <OBJECT> tag.

If you are using the visual object, XFiledisplays a file list in an ActiveX Control window that supports drag and drop. The following code is an example of using a visual object:

....
<object classid="CLSID:230C3D02-DA27-11D2-8612-00A0C93EEA3C" id="AXFFile"
style="height: 200px; left: 0px; top: 0px; width: 400px"
codebase="/saxfilesamples/saxfile.cab" viewastext>
</object>
....

For a non-visual object, the code looks like the following:

....
<object classid="clsid:C3A57B60-C117-11D2-BD9B-00105A0A7E89"
codebase="/saxfilesamples/saxfile.cab" id="XFRequest">
....

You can set properties through subroutines:

....
<script language="vbscript">

Sub UploadButton_OnClick()

'-- Set the URL where we want to send the data by
'-- using the CurrentURL property
XFRequest.CurrentURL = _
"http://localhost/SAXFileSamples/asp/post/onefile/formresp.asp"

'-- Add the file to the upload
XFRequest.AddFile "C:\boot.ini", "FileName1"

'-- Start the transfer
XFRequest.Start
End Sub

</script>
....

For more examples, check out the samples provided as part of the FileUpdistribution. See Programmer's Samples for a list of the contents of the Samples directory.

Top


FileUp Object

The FileUp object is the principal object used for all of FileUp's functions including file upload, file download, and database manipulation.

To use any upload or download function in SoftArtisans FileUp, you must create an instance of the FileUp object.

To do this in ASP, use the built-in Server.CreateObject function.

<% Set fileUpload = Server.CreateObject("SoftArtisans.FileUp") %>

After that, all methods and properties are available to you.

In ASP.NET, you should include the SoftArtisans.Net namespace. It is also recommended that you declare an object for FileUp prior to a try...catch...finallycode block, and then, instatiate FileUp within the try section of the block. When FileUp is instantiated, pass it the context of the Request.

When you are finished using the FileUp object, you must remember to call Dispose() on the FileUp object in the finally section.

For more information on the technical reasons that this structure is advised, please see Properly Disposing of Resources in .NET

C# using SoftArtisans.Net;

...(namespace, class, and other declaration code, )....

private void ProcessUpload()
{
//--- Declare the FileUp object
FileUp fileUpload = null;

try
{
fileUpload = new FileUp (Context);

...(upload processing code)

     }
catch (Exception ex)
{

...(error handling code here)

     }
finally
{
//--- Always call Dispose
//--- in the finally block
if (fileUpload != null)
fileUpload.Dispose();
fileUpload = null;
}
}
VB.NET Imports SoftArtisans.Net

...(namespace, class, and other declaration code, )....

Private Sub ProcessUpload()
'--- Declare the FileUp object
Dim fileUpload As FileUp
Try
fileUpload = New FileUp (Context)

...(upload processing code)

     Catch ex As System.Exception

...(error handling code here)

     Finally
'--- Always call FileUp.Dispose
'--- in the finally block
If Not (fileUpload Is Nothing) Then
fileUpload.Dispose()
End If
fileUpload = Nothing
End Try
End Sub

(...)


FileUp Object Methods

Delete Method

Dispose Method V4

Flush Method

NextProgressID Property

ResetAllProgressID Property

ResetProgressID Property

Save Method

SaveAs Method

SaveAsBlob Method

SaveAsBlob Override Method V4

SaveBinaryAs Method

SaveInVirtual Method

SaveRecursive Method

TransferBlob Method

TransferFile Method


Delete

Delete Method

Object: SoftArtisans.FileUp
Syntax: Delete([in,optional] Filename As String)
Description:

This method deletes a file from the web server's hard disk.

If you specify a Filename, it must contain the entire valid path.

If you do not specify a Filename, the current uploaded file is deleted. This allows you to effectively cancel an upload. If there is more than one file being uploaded in a single page, only the first one is deleted.

To delete multiple files in a single upload, there is an equivalent method for each file object, i.e., fileUpload.Form("File1").Delete. Please see SAFile.Delete().

Examples:
ASP <%
fileUpload.Delete Server.MapPath("Uploads\UploadedFile.txt")
%>
C# | fileUpload.Delete(Server.MapPath("Uploads\\UploadedFile.txt"));
VB.NET | fileUpload.Delete(Server.MapPath("Uploads\UploadedFile.txt"))

ASP <%
fileUpload.SaveAs strFileName
If Err = 0 Then
Response.Write("Upload saved successfully to " &_
fileUpload.ServerName & "<br />")

'--- Perform some other processing here,
'--- such as writing to a database.
'--- Assume some error occurred
'--- delete the uploaded file.
fileUpload.Delete

If Err <> 0 Then
Response.Write("An error occurred when attempting " & _
to delete the uploaded file.<br />")
Else
Response.Write("Uploaded file has been deleted.<br />")
End If

End If
%>
C# fileUpload.SaveAs(strFileName);
results.Append("Upload saved successfully to " +
fileUpload.ServerName & "<br />");

//--- Perform some other processing here,
//--- such as writing to a database.

try
{
//--- Assume some error occurred
//--- delete the uploaded file.
fileUpload.Delete();
Results.Append("Uploaded file has been deleted.<br />");
}
catch (Exception e)
{
Results.Append("An error occurred when attempting " +
"to delete the uploaded file.<br />");
}
VB.NET fileUpload.SaveAs(strFileName)
results.Append("Upload saved successfully to " + _
fileUpload.ServerName & "<br />")

'--- Perform some other processing here,
'--- such as writing to a database.

Try
//--- Assume some error occurred
//--- delete the uploaded file.
fileUpload.Delete()
Results.Append("Uploaded file has been deleted.<br />")
Catch (Exception e)
Results.Append("An error occurred when attempting " + _
"to delete the uploaded file.<br />")
End Try


Dispose

Dispose Method

Object: SoftArtisans.FileUp
Syntax: Dispose()
Description:

This method is only available for use in ASP.NET. It is not required in an ASP environment. Since FileUp is not a pure .NET assembly, but rather a COM component with .NET support, you must explicitly call Dispose in order to properly free resources that it may be using.

Examples:
C# using SoftArtisans.Net;

...(namespace, class, and other declaration code, )....

private void ProcessUpload()
{
//--- Declare the FileUp object
FileUp fileUpload = null;

try
{
fileUpload = new FileUp (Context);

...(upload processing code)

     }
catch (Exception ex)
{

...(error handling code here)

     }
finally
{
//--- Always call Dispose
//--- in the finally block
if (fileUpload != null)
fileUpload.Dispose();
fileUpload = null;
}
}
VB.NET Imports SoftArtisans.Net

...(namespace, class, and other declaration code, )....

Private Sub ProcessUpload()
'--- Declare the FileUp object
Dim fileUpload As FileUp
Try
fileUpload = New FileUp (Context)

...(upload processing code)

     Catch ex As System.Exception

...(error handling code here)

     Finally
'--- Always call FileUp.Dispose
'--- in the finally block
If Not (fileUpload Is Nothing) Then
fileUpload.Dispose()
End If
fileUpload = Nothing
End Try
End Sub

(...)


Flush

Flush Method

Object: SoftArtisans.FileUp
Syntax: Flush()
Description:

This method flushes the entire input HTTP Post input stream.

Use this method if you explicitly want to empty the entire input stream without performing any saves at all.

The following scenario illustrates the usefulness of this method:

  • A user attempts to upload a file larger than 48 KB
  • On the server, IIS reads the first 48 KB and then invokes FileUp
  • An error or exception occurs during the processing of the script (from IIS, FileUp,or some other processing in your script).
  • The browser reports a "Network Error" because it is still trying to send more data than was read by the server. The browser never displays the error message from the server because it considers that the request was never completed.

Use the Flush method during error handling to ensure that the entire input stream is cleared.

If you invoke any Save method (Save, SaveAs, SaveAsBlob, SaveBinaryAs), then the entire input stream will be cleared anyway.

It is never harmful to invoke the Flush method.
Examples:
ASP <%
fileUpload.Flush
%>
C# | fileUpload.Flush();
VB.NET | fileUpload.Flush()


NextProgressID

NextProgressID Method

Object: SoftArtisans.FileUp
Syntax: NextProgressID()
Description:

This method returns the next unused ProgressID. Unique progress IDs are necessary to track accurate progress for multiple simultaneous uploads on the same webserver. See the ProgressID property for more information.

Examples:
ASP <%
'--- Obtain the next progress ID to be used for an upload.
fileUpload.ProgressID = fileUpload.NextProgressID
%>
C# //--- Obtain the next progress ID to be used for an upload.
fileUpload.ProgressID = fileUpload.NextProgressID();
VB.NET '--- Obtain the next progress ID to be used for an upload.
fileUpload.ProgressID = fileUpload.NextProgressID()

Because progress indication requires the coordination of several scripts, please see the appropriate Programmer's Guide for a complete sample the demonstrates the use of the FileUp NextProgressID method.

  • Programmer's Guide for ASP Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator


ResetAllProgressID

ResetAllProgressIDs Method

Object: SoftArtisans.FileUp
Syntax: ResetAllProgressIDs()
Description:

This method will reset all Progress IDs.

ResetAllProgressID will reset every progress ID so that the Progress Indicator object will be cleared of data from all past and current file transfers. This method takes no parameters. See the ProgressID property for more information.

Note: ResetAllProgressID is implemented on NT4 with IIS4 or higher, and Windows 2000.
Examples:
ASP | <% fileUpload.ResetAllProgressIDs %>
C# | fileUpload.ResetAllProgressIDs();
VB.NET | fileUpload.ResetAllProgressIDs()


ResetProgressID

ResetProgressID Method

Object: SoftArtisans.FileUp
Syntax: ResetProgressID([in] ProgressID As Long)
Description:

This method will reset one Progress ID.

Resetting a progress ID will ensure that the Progress Indicator Object does not store data from file transfers which have already been completed or interrupted.

See the ProgressID property for more information.

Note: ResetProgressID is implemented on NT4 with IIS4 or higher, and Windows 2000.
Examples:

To reset the current Progress ID:

ASP <%
'--- Create an instance of SoftArtisans FileUp
Set fileUpload = Server.CreateObject(SoftArtisans.FileUp)

'--- Set the default path to store uploaded files.
fileUpload.Path = "C:\temp"

'--- Assign a ProgressID to this upload
fileUpload.ProgressID = fileUpload.NextProgressID

'--- Reset the current ProgressID
fileUpload.ResetProgressID fileUpload.ProgressID
%>
C# //--- Create an instance of SoftArtisans FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set the default path to store uploaded files.
fileUpload.Path = "C:\\temp";

//--- Assign a ProgressID to this upload
fileUpload.ProgressID = fileUpload.NextProgressID();

//--- Reset the current ProgressID
fileUpload.ResetProgressID(fileUpload.ProgressID);
VB.NET '--- Create an instance of SoftArtisans FileUp
Dim fileUpload As New FileUp(Context)

'--- Set the default path to store uploaded files.
fileUpload.Path = "C:\temp"

'--- Assign a ProgressID to this upload
fileUpload.ProgressID = fileUpload.NextProgressID()

'--- Reset the current ProgressID
fileUpload.ResetProgressID(fileUpload.ProgressID)

To reset a particular Progress ID by number:

ASP | <% fileUpload.ResetProgressID 6 %>
C# | fileUpload.ResetProgressID(6);
VB.NET | fileUpload.ResetProgressID(6)


Save

Save Method

Object: SoftArtisans.FileUp
Syntax: Save()
Description:

This method saves an uploaded file to the Web server's hard disk using the user's original filename. If an upload contains more than one file, only the first one is saved.

To save multiple files in a single upload, use the method Save method of the SAFile object, instead: File.Save().

To use the Save method, you must set the Path property.

By default, an uploaded file will overwrite a file on the server with the same name. To prevent this, set OverwriteFilesto False.

Examples:

The following saves the upload on the Web server at C:\Uploads:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload at C:\Uploads
fileUpload.Path = "C:\Uploads"

'--- Save upload at C:\Uploads
fileUpload.Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default Save location to C:\Uploads
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = "C:\\Uploads";

//--- Save upload to C:\Uploads
fileUpload.Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set default Save location to C:\Uploads
'--- (Cache location is set in registry since HttpModule is used
'--- with .NET)
fileUpload.Path = "C:\Uploads"

'--- Save upload to C:\Uploads
fileUpload.Save()

The following saves the upload to a network shared drive:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload at \\FileServer\Uploads
fileUpload.Path = "\\FileServer\Uploads"

'--- Save upload to \\FileServer\Uploads
fileUpload.Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default Save location to \\FileServer\Uploads
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = @"\\FileServer\Uploads";

//--- Save upload to \\FileServer\Uploads
fileUpload.Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set default Save location to \\FileServer\Uploads
'--- (Cache location is set in registry since HttpModule is used '--- with .NET)
fileUpload.Path = "\\FileServer\Uploads"

'--- Save upload to \\FileServer\Uploads
fileUpload.Save()


SaveAs

SaveAs Method

Object: SoftArtisans.FileUp
Syntax: SaveAs([in] Filename As String)
Description:

This method saves an uploaded file to the Web server's hard disk. If an upload contains more than one file, only the first one is saved.

To save multiple files in a single upload, use the method SAFile object's SaveAs() method: File.SaveAs.

SaveAs takes a physical path for its Filename argument. This can be provided in one of two ways:

  • Provide a complete physical path and file name.
  • Provide only a name for the file. SaveAs will take the directory path from the Path property.

If no path is specified (e.g., fileUpload.SaveAs "FileX.ext"), the value of the Path property is used. For more efficient processing, it is recommended that you always use set the Path property before saving any files.

If the Filename parameter includes a file path, it must specify a physical path (for example "C:\UploadDir\FileX.ext"). You cannot pass a virtual path to the SaveAs method.

By default, an uploaded file will overwrite a file on the server with the same name. To prevent this, set OverwriteFilesto False.

Examples:

The following sets the Path property to C:\Temp and saves the upload on the Web server at C:\Uploads:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload to C:\Temp
fileUpload.Path = "C:\Temp"

'--- Save upload to C:\Uploads using the original filename of the
'--- file
fileUpload.SaveAs "C:\Uploads\" & fileUpload.Form("File1").ShortFileName
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default Save location to C:\Temp
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = "C:\\Temp";

//--- Save upload to C:\Uploads using the original filename of the
//--- file
fileUpload.SaveAs("C:\\Uploads\\" + fileUpload.Form("File1").ShortFileName);
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- Set default Save location to C:\Temp
'--- (Cache location is set in registry since HttpModule is used
'--- with .NET)
fileUpload.Path = "C:\Temp"

'--- Save upload to C:\Uploads using the original filename of the
'--- file
fileUpload.SaveAs("C:\Uploads\" + fileUpload.Form("File1").ShortFileName)

The following sets the Path property to C:\Temp and saves the upload to a network shared drive:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload to C:\Temp
fileUpload.Path = "C:\Temp"

'--- Save upload to \\FileServer\Uploads using the original
'--- filename of the file
fileUpload.SaveAs "\\FileServer\Uploads" & fileUpload.Form("File1").ShortFileName
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default Save location to C:\Temp
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = "C:\\Temp";

//--- Save upload to \\FileServer\Uploads using the original
//--- filename of the file
fileUpload.SaveAs("\\FileServer\Uploads\" & fileUpload.form("File1").ShortFileName);
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set default Save location to C:\Temp
'--- (Cache location is set in registry since HttpModule is used
'--- with .NET)
fileUpload.Path = "C:\Temp"

'--- Save upload to \\FileServer\Uploads using the original '--- filename of the file
fileUpload.SaveAs("\\FileServer\Uploads\" + fileUpload.form("File1").ShortFileName)


SaveAsBlob

SaveAsBlob Method

Object: SoftArtisans.FileUp
Syntax: SaveAsBlob([in] ADOField)
Description:

This method saves an uploaded file to a database.

AppendChunk method. Any OLEDB provider that supports the AppendChunk method can be the destination of a SaveAsBlob. FileUpuses late binding to find the AppendChunk method of the recordset member and writes the data using this method. Note that even char and varchar type fields support AppendChunk, although the size is significantly limited.

For Microsoft SQL Server, the column should be of 'image' or 'text' type. his distribution includes a sample SQL script that you can use to create tables for use in uploading files. See the Setup Instructions for uploading to a database on the server.

For Microsoft Access, the column should be 'OLE Object'. You can use the sample Access database included with this distribution (in the Samples directory) for downloading and uploading files.

When writing to BLOB (Binary Large OBject) fields, the ADO Recordset's cursor type must be adOpenDynamic (i.e., 2).

Any size limitations of the BLOB field is imposed by the database.

The uploaded data is stored exactly as sent, with no interpretation.

If there is more than one file being uploaded in a single page, only the first one is saved.

To save multiple files in a single upload, there is an equivalent method for each file object, i.e., fileUpload.Form("File1").SaveAsBlob rs("FileCol").

By default, an uploaded file will overwrite a file on the server with the same name. To prevent this, set OverwriteFilesto False.

Performance Considerations When Uploading to a Database
In general, uploading to a database instead of a file is less efficient, both in terms of disk space and processor time. Due to the caching necessary when processing multiple form and file elements, the upload is saved to a file and then imported into the database. The temporary cache file is then deleted. Uploading to a database also consumes significant memory resources. It is possible that you will get errors like the following when uploading to a database:

"There is insufficient system memory to run this query."

Uploading to a database is best when there are many small files that you wish to catalogue, such as small graphic images. Large uploads are generally best stored in native files.
See Also: ADO.NET and SaveAsBlob
Examples:
ASP <%
Set rsBlob = Server.CreateObject("ADODB.Recordset")
rsBlob.Open "SimpleBlobTable", "AccessUpload", 2, 3

'---
'--- Add new record and update
'---
rsBlob.AddNew
fileUpload.SaveAsBlob rsBlob.Fields("FileCol")

rsBlob.Update
rsBlob.Close
Set rsBlob = Nothing
'...
%>


SaveAsBlob Override

SaveAsBlob Override Method

Object: SaveAsBlob Override Method
Syntax: SaveAsBlob(SqlCommand SqlCmd, SqlParameter InParam, SqlParameter OutParam)
Description:

FileUp supports chunked database inserts and updates with ADO.NET in SQL Server. This is done using SQL Server's UPDATETEXT command and FileUp's SaveAsBlob override to write chunks of data to a BLOB column.

By default, an uploaded file will overwrite a file on the server with the same name. To prevent this, set OverwriteFilesto False.

See Also: Chunked Inserts and Updates in ADO.NET
Examples:
ASP N/A
C# //--- Create an System.Data.SqlClient.SqlCommand reference
//--- using the 'UPDATETEXT' sql command, creating 'Pointer',
//--- 'Offset', and 'Delete' parameters so that FileUp
//--- can properly chunk data to the database column.
SqlCommand cmd = new SqlCommand("UPDATETEXT " +
"Categories.Picture @Pointer @Offset " +
"@Delete WITH LOG @Bytes", cn);
SqlParameter inParam = cmd.Parameters.Add("@Pointer",
SqlDbType.Binary, 16);

//--- Call SaveAsBlob.
fileUpload.SaveAsBlob(cmd, inParam, outParam);
VB.NET '--- Create an System.Data.SqlClient.SqlCommand reference
'--- using the 'UPDATETEXT' sql command, creating 'Pointer',
'--- 'Offset', and 'Delete' parameters so that FileUp
'--- can properly chunk data to the database column.
Dim cmd As New SqlCommand("UPDATETEXT _
Categories.Picture @Pointer @Offset _
@Delete WITH LOG @Bytes", cn)
Dim inParam As SqlParameter = cmd.Parameters.Add("@Pointer",_
SqlDbType.Binary, 16)

'--- Call SaveAsBlob.
fileUpload.SaveAsBlob(cmd, inParam, outParam)


SaveBinaryAs

SaveBinaryAs Method

Object: SoftArtisans.FileUp
Syntax: SaveBinaryAs([in] Filename As String)
Description:

This method saves the raw HTTP Post stream to the web server's hard disk without any interpretation.

If no path is specified (for example, fileUpload.SaveBinaryAs "FileX.ext"), the value of the Path property is used. For more efficient processing, it is recommended that you always use set the Path property before saving any files.

If the Filename parameter includes a file path, it must specify an absolute path (for example, "C:\UploadDir\FileX.ext"). You cannot pass a relative path to the SaveBinaryAs method.

The SaveBinaryAs method cannot be used in conjunction with other methods that interpret the HTTP Post stream (for example, methods that get form values or save a decoded upload to disk).

In ASP.NET, this method can be useful in determining in the HttpModule is configured correctly and properly stripping the uploaded file's binary out of the Request and replacing it with a pointer to the cached file.

Examples:

The following sets the Path property to C:\Temp and saves the raw HTTP Post stream on the Web server at C:\Uploads:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload to C:\Temp
fileUpload.Path = "C:\Temp"

'--- Save raw stream to C:\Uploads\file.txt
fileUpload.SaveBinaryAs "C:\Uploads\file.txt"
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default save location to C:\Temp
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = "C:\\Temp";

//--- Save raw stream to C:\Uploads\file.txt
fileUpload.SaveBinaryAs("C:\\Uploads\\file.txt");
VB.NET '--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

'--- Set default save location to C:\Temp
'--- (Cache location is set in registry since HttpModule is used
'--- with .NET)
fileUpload.Path = "C:\Temp"

'--- Save raw stream to C:\Uploads\file.txt
fileUpload.SaveBinaryAs("C:\Uploads\file.txt")


SaveInVirtual

SaveInVirtual Method

Object: SoftArtisans.FileUp
Syntax: SaveInVirtual([in] VirtualLocation As String)
Description:

This method saves an uploaded file to the web server's hard disk in a location specified by the virtual directory or filename in a virtual directory.

SaveInVirtual uses the ASP or ASP.NET Server.MapPath() function internally. The virtual directory is then mapped to a physical directory for FileUp to use. You must be certain that the physical directory to which the virtual path maps, has the correct NTFS permissions to save the file. For more information on these permissions, please see the "Configuration and Application Planning" section this documentation set and read the permissions topics that apply to the language and configuration that you are using. As with the MapPath function, you specify either a virtual directory or a filename. If you specify a filename, it is resolved in the current virtual directory.

The Web Administrator can disable all other save methods except SaveInVirtual. This prevents the Web Developer from writing to non-virtual directory locations on the server. See Disabling FileUpfeatures .

When using the SaveInVirtual method of the FileUp object, if there is more than one file being uploaded in a single page, only the first one is saved.

To save multiple files in a single upload, there is an equivalent method for each file object, i.e., fileUpload.Form("File1").SaveInVirtual "filename". Please see SAFile.SaveInVirtual.

If the upload destination folder is a virtual directory, a malicious user may be able to upload an infected file to the directory and launch it through the Web. To prevent this, use a folder that is not a virtual directory as the upload destination location.
Examples:

Specify a virtual directory, but keep the user's original filename:

ASP <%
fileUpload.SaveInVirtual "./Uploads"
%>
C# | fileUpload.SaveInVirtual("./Uploads");
VB.NET | fileUpload.SaveInVirtual("./Uploads")

Specify a virtual directory that includes the file name:

ASP <%
fileUpload.SaveInVirtual "./Uploads/Myfile.ext"
%>
C# | fileUpload.SaveInVirtual("./Uploads/Myfile.ext");
VB.NET | fileUpload.SaveInVirtual("./Uploads/Myfile.ext")


SaveRecursive

SaveRecursive Method

Object: SoftArtisans.FileUp
Syntax: SaveRecursive()
Description:

This method saves a group of files uploaded to the Web server's hard disk using the user's original file names and folder structure. For instance, if a user uploads the c:\Inetpub directory, all the files in that directory, as well as any files in any subdirectories, are saved to the hard drive with the same folder structure.

This method works in conjunction with SoftArtisans XFile'sclient which transmits an additional header called X-RelativeFileName. Standard browsers such as Internet Explorer or Netscape Navigator cannot recursively upload directories at the current time.

Let's say a user has a file called C:\Temp\user\simple.doc, and chooses AddDirectoryRecursive c:\Temp. The uploaded data will include a header for this file:

X-RelativeFileName: user\simple.doc

Using SaveRecursive, the file is saved on the server side as {upload.path}\user\simple.doc.

To use the SaveRecursive method, you must set the Path property.

By default, an uploaded file will overwrite a file on the server with the same name. To prevent this, set OverwriteFilesto False.

Examples:

The following saves the upload on the Web server at C:\Uploads:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload to C:\Uploads
fileUpload.Path = "C:\Uploads"

'--- Save the recursive upload to C:\Uploads
fileUpload.SaveRecursive
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default save location to C:\Uploads
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = "C:\\Uploads";

//--- Save the recursive upload to C:\Uploads
fileUpload.SaveRecursive();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set default save location to C:\Uploads
'--- (Cache location is set in registry since HttpModule is used
'--- with .NET)
fileUpload.Path = "C:\Uploads"

'--- Save the recursive upload to C:\Uploads
fileUpload.SaveRecursive()


TransferBlob

TransferBlob Method

Object: SoftArtisans.FileUp
Syntax: TransferBlob([in] ADOField)
Description:

This method transfers (downloads) a file from a database to the browser.

The ADOField argument must point to a valid ADO Field object that supports the GetChunk method. Any OLEDB provider that supports the GetChunk method can be used with TransferBlob. FileUpuses late binding to find the GetChunk method of the recordset member and writes the data that way.

For Microsoft SQL Server, the column should be of 'image' or 'text' type. This distribution includes a sample SQL script that you can use to create tables for use in uploading files. See the Setup Instructions for uploading to a database on the server.

For Microsoft Access, the column should be 'OLE Object'. You can use the sample Access database included with this distribution (in the Samples directory) for downloading and uploading files. It comes pre-populated with a record containing a Microsoft Word document.

When reading from BLOB (Binary Large OBject) fields, the ADO Recordset's cursor type should be set to adOpenStatic (3).

Typically, you set the content (MIME) type before executing this method.

The data is sent exactly as stored, with no interpretation and no Unicode to multi-byte conversion.

Note on IE 4: Internet Explorer 4 does not recognize MIME types supplied by the web server. Unfortunately, this does not comply with the HTTP protocol. Instead, IE uses the extension found at the end of the URL to determine the MIME type. So to download to IE 4, you must "fool" it with a bogus extension at the end of your URL. Also, IE ignores the MIME-standard content-disposition header that allows the web developer to pre-set the filename contained the user's Save Dialog box. Perhaps with enough grassroots support, Microsoft will modify their products to process these standard MIME headers. To work around this problem, you could set the URL to:

http://myserver/mydownload.asp?bogus=filename.ext

or

http://myserver/mydocgenerator.asp?bogus=file.doc

We recommend that you either upgrade to IE 5, which solves the problem, or use SoftArtisans XFile for downloading.

See Also: ADO.NET and TransferBlob
Examples:
ASP <%
Response.ContentType = "application/msword"

'--- Create an instance of the file download component
Set fileDownload = Server.CreateObject("SoftArtisans.FileUp")

'--- Do the transfer. Open a connection to the database. This sample
'--- uses the same Access database as in Samples/uploadmdb.
'--- That database is pre-populated with the sample.doc file.
Set rsBlob = Server.CreateObject("ADODB.RecordSet")

'--- Open Recordsets
rsBlob.Open "SimpleBlobTable", "AccessUpload", 3, 3
rsBlob.MoveFirst

'--- Download the File
fileDownload.TransferBlob rsBlob.Fields("filecol")
%>


TransferFile

TransferFile Method

Object: SoftArtisans.FileUp
Syntax: TransferFile([in] Filename As String)
Description:

This method transfers (downloads) a file from the web server's hard disk to the browser. What differentiates this functionality from a simple GET request is that TransferFile takes a physical path for the file location, allowing files to be kept in a non-browsable location.

The filename must contain the entire valid path. You can use Server.MapPath to map virtual roots to physical directories, if necessary; However, regardless of the path used, you must still have appropriate NTFS permissions for FileUp to retrieve the file from its location. Please see the section appropriate to your programming language in the Configuration and Application Settings section of this documentation set.

Typically, in addition to using TransferFile, you would also set the appropriate Response headers to inform the browser how to handle the incoming file. For a detailed tutorial and complete code sample on using the TransferFile method, please see the "Getting Started" section appropriate to your programming language:

  • Secure Downloading in ASP
  • Secure Downloading in ASP.NET

Note on browser compatibility:

Different versions of various browsers may interpret download information differently. The following is a list of known behavior that you should be careful to test for.

  • Internet Explorer 4 does not recognize MIME types supplied by the web server. Unfortunately, this does not comply with the HTTP protocol. Instead, IE uses the extension found at the end of the URL to determine the MIME type. So to download to IE 4, you must "fool" it with a bogus extension at the end of your URL.

    http://myserver/mydownload.asp?bogus=filename.ext or
    http://myserver/mydocgenerator.asp?bogus=file.doc

  • Internet Explorer for Mac may interpret the Response headers incorrectly and provide the name of the download script in the SaveAs dialog box instead of the file name. You will need to instruct users to Save the file with the correct name if this occurs.

  • Internet Explorer for Windows version 5.5, SP1 contained the same problem as mentioned above for Internet Explorer for Mac. This was correct in a subsequent service pack and in later releases of IE.

  • For the most current and complete list of known browser issues, please check the SoftArtisans Knowledge Baseon a regular basis.
Examples:
ASP <%
fileDownload.TransferFile "C:\MyServerDir\sample.doc"
%>
C# | fileDownload.TransferFile(@"C:\MyServerDir\sample.doc");
VB.NET | fileDownload.TransferFile("C:\MyServerDir\sample.doc")

For a complete sample, see:

  • Secure Downloading in ASP
  • Secure Downloading in ASP.NET


FileUp Object Properties

BufferSize Property

CodePage Property

ContentDisposition Property

ContentTransferEncoding Property

ContentType Property

CreateNewFile Property

DateLastModified Property

DateLastModifiedUTC Property

ExpirationDate Property

Form Property

FormEx Property

IsEmpty Property

Item Property

MaxBytes Property

MaxBytesToCancel Property

MimeVersion Property

OverWriteFiles Property

Path Property

PerConnectionBandwidthLimit Property

PerServerBandwidthLimit Property

ProgressID Property

ServerName Property

ShortFilename Property

TotalBytes Property

UseDateLastModified Property

UseIE5Fix Property

UseMemory Property

UserFilename Property

Version Property


BufferSize

BufferSize Property

Object: SoftArtisans.FileUp
Syntax: BufferSize[=SizeInBytes As Long]
Type: Long
Read/Write: Read/Write
Description:

This property sets the data reading buffer for uploads.

BufferSize is set to 63K by default. The BufferSize can be adjusted between 2K to 200K. The property should be set in bytes, not in KB. In order to calculate bytes, multiply the number of KB by 1024. smaller the BufferSize setting, the more frequently the progress indicator will be updated.

Increasing the BufferSize from the default setting may allow for faster uploading of large files.

Set BufferSize after creating an instance of the FileUp object, and before referencing any files or form elements.

Note: Decreasing the value of BufferSize will produce slower uploads.

Note: When using the HttpModule with .NET uploads, this property will have little affect. Since the actual file will be stripped out by the HttpModule, the BufferSize will only apply to the resulting, much smaller request.
Examples:
ASP <%
'--- Create an instance of SoftArtisans FileUp
Set fileUpload = Server.CreateObject(SoftArtisans.FileUp)

'--- Set the default path to store uploaded files
fileUpload.Path = "C:\temp"

'--- Reduce the BufferSize to 30 KB
fileUpload.BufferSize = 30 * 1024
'--- Or, calculate the value in bytes
'fileUpload.BufferSize = 30720
%>
ASP.NET N/A


CodePage

CodePage Property

Object: SoftArtisans.FileUp
Syntax: CodePage[=Language Code As Long]
Type: Long
Read/Write: Read/Write
Description:

Sets or returns the language of the file(s) or folder(s) being transferred. On Windows NT 4.0 and higher, SoftArtisans FileUp is Unicode compliant, enabling the transfer of data between systems, regardless of language, without the risk of data corruption. By setting FileUp's Codepage property, you will be able to preserve file names in their original language.

FileUp's Codepage property specifies a Unicode language code for correctly storing the file name internally. To display the filename correctly, set the HTML tag's Charset attribute as well.

When client and server share the same language platform, you do not need to set Codepage. For heterogeneous language support, use Codepage 65001 and charset UTF-8 (Unicode).

For a complete list of Codepage values, see Microsoft's Character Set Recognition reference.

See also, Multilingual Support.

Examples:

If you are uploading a Japanese file with a Japanese filename, include the following in the HTML of your upload page and upload processing page, if different:

ASP/ASP.NET <meta http-equiv="Content-Type"
content="text/html; charset=iso-2022-jp" />

In the upload processing page code, include the following:

ASP <%
fileUpload.CodePage = 50220
%>
C# | fileUpload.CodePage = 50220;
VB.NET | fileUpload.CodePage = 50220


ContentDisposition

ContentDisposition Property

Object: SoftArtisans.FileUp
Syntax: ContentDisposition
Type: String
Read/Write: Read Only
Description:

This property contains the MIME Content Disposition of the data. This should always be "form-data" when using a browser that supports RFC1867 uploads.

Use this parameter to determine if the browser supports this upload mechanism.

Even if there are multiple files in an upload, every file's Content Disposition should still be "form-data".

If there is more than one file being uploaded in a single page, only the first one is displayed.

To examine the content disposition of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("File1").ContentDisposition.

Examples:
ASP <% If fileUpload.ContentDisposition <> "form-data" Then %>
Your upload did not succeed, most likely because your browser
does not support upload via this mechanism.
<% End If %>
C# if (fileUpload.ContentDisposition != "form-data")
{
results.Append("Your upload did not succeed, most likely " +
"because your browser does not support upload via " +
"this mechanism.");
}
VB.NET If (fileUpload.ContentDisposition <> "form-data") Then
results.Append("Your upload did not succeed, most likely " + _
"because your browser does not support upload via " + _
"this mechanism.")
End If


ContentTransferEncoding

ContentTransferEncoding Property

Object: SoftArtisans.FileUp
Syntax: ContentTransferEncoding
Type: String
Read/Write: Read Only
Description:

This property is typically blank, but may contain the MIME Content Transfer Encoding.

If there is more than one file being uploaded in a single page, only the first one will be displayed.

To examine the Content Transfer Encoding of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("File1").ContentTransferEncoding.

Examples:
ASP The Content Transfer Encoding of this upload is:
<%=fileUpload.ContentTransferEncoding%>.
C# results.Append("The Content Transfer Encoding of this upload is: " +
fileUpload.ContentTransferEncoding);
VB.NET results.Append("The Content Transfer Encoding of this upload " + _
"is: " + fileUpload.ContentTransferEncoding)


ContentType

ContentType Property

Object: SoftArtisans.FileUp
Syntax: ContentType
Type: String
Read/Write: Read Only
Description:

This property contains the MIME Content Type of the file, which is useful in determining the contents of the file.

It has been our experience that Netscape Navigator version 4 returns creative and diverse Content Types, depending on the file being uploaded. Internet Explorer typically returns the lowest common denominator, which is "application/octet-stream".

If there is more than one file being uploaded in a single page, only the first one will be displayed.

To examine the Content Type of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("File1").ContentType.

Examples:
ASP The Content Type of this upload is: <%=fileUpload.ContentType%>.
C# results.Append("The Content Type of this upload is: " +
fileUpload.ContentType);
VB.NET results.Append("The Content Type of this upload is: " + _
fileUpload.ContentType)


CreateNewFile

CreateNewFile Property

Object: SoftArtisans.FileUp
Syntax: CreateNewFile[=Boolean]
Type: Boolean
Read/Write: Read/Write
Description:

This property can generate unique file names.

If CreateNewFile is set to TRUE, FileUp will automatically append an underscore and a number between 0 and 999 to the name of the file being uploaded, if a file with the same name already exists in the upload directory.

CreateNewFile is set to FALSE by default. To use this property, set CreateNewFile to TRUE, after creating an instance of the FileUp object, and before referencing any form elements.

Note: Because this property must be set before the upload contents are cached, this property is ineffective in an ASP.NET environment when the HttpModule is employed.
Examples:
ASP <%
'--- Create an instance of SoftArtisans FileUp.
Set fileUpload = Server.CreateObject(SoftArtisans.FileUp)

'--- Set the default path to store uploaded files.
fileUpload.Path = "C:\temp"

'--- Instruct FileUp to generate a unique file name if the
'--- file's original name already exists on the server.
'--- Important: Set CreateNewFile before referencing form elements.
fileUpload.CreateNewFile = True

'--- Save the file.
fileUpload.Save

'--- Write out its new, unique name.
Response.Write "File saved as: " & fileUpload.ServerName
%>
ASP.NET N/A


DateLastModified

DateLastModified Property

Object: SoftArtisans.FileUp
Syntax: DateLastModified
Type: Date
Read/Write: Read Only
Description:

If UseDateLastModified is set to True, DateLastModified will return the last modification date of the file transmitted by the user. The date is displayed using the local time zone. For the UTC date of the file, see the DateLastModifiedUTC property.

The DateLastModified property only works if the client-upload software sends this information. Neither Netscape Navigator nor Microsoft Internet Explorer send the file's modification date. SoftArtisans XFile transmits this information by inserting the "X-Last-Modified" header in the Request, when XFile's [XFRequest].UseXLastModified property is set to True.

The file modification date is always sent in GMT format to account for time zone differences between the browser and server.

If you are using a different upload client, use the following header to send the Last Modified date:

X-Last-Modified: Fri Dec 04 10:29:02 GMT 1998

Which is defined as follows:

date-time = day date time 4DIGIT ; Dow Mmm dd hh:mm:ss zzz yyyy day = "Mon" /
            "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" date = month 2DIGIT ; month day month
            = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct"
            / "Nov" / "Dec" time = hour zone ; ANSI hour = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00
            - 23:59:59 zone = "UT" / "GMT" ; Universal Time

See also: FileUp.DateLastModified.

Examples:

ASP The Date Last Modified of this upload is:
<%=fileUpload.DateLastModified%>.
C# results.Append("The Date Last Modified of this upload is: " +
((DateTime)fileUpload.DateLastModified).ToString());
VB.NET results.Append("The Date Last Modified of this upload is: "+ _
fileUpload.DateLastModified.ToString())


DateLastModifiedUTC

DateLastModifiedUTC Property

Object: SoftArtisans.FileUp
Syntax: DateLastModifiedUTC
Type: Date
Read/Write: Read Only
Description:

If UseDateLastModified is set to True, DateLastModifiedUTC will return last modification date of the file transmitted by the user. The date is displayed using Universal Time (UTC, or GMT). For the local date of the file, see the DateLastModified property.

The DateLastModified property only works if the client-upload software sends this information. Neither Netscape Navigator nor Microsoft Internet Explorer send the file's modification date. SoftArtisans XFile transmits this information by inserting the "X-Last-Modified" header in the Request, when XFile's [XFRequest].UseXLastModified property is set to True.

The file modification date is always sent in GMT format to account for time zone differences between the browser and server.

If you are using a different upload client, use the following header to send the Last Modified date:

X-Last-Modified: Fri Dec 04 10:29:02 GMT 1998

Which is defined as follows:

date-time = day date time 4DIGIT ; Dow Mmm dd hh:mm:ss zzz yyyy day = "Mon" /
            "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" date = month 2DIGIT ; month day month
            = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct"
            / "Nov" / "Dec" time = hour zone ; ANSI hour = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00
            - 23:59:59 zone = "UT" / "GMT" ; Universal Time

Examples:

ASP The Date Last Modified (UTC) of this upload is
<%=fileUpload.DateLastModifiedUTC%>.
C# results.Append("The Date Last Modified (UTC) " +
"of this upload is: " +
((DateTime)fileUpload.DateLastModifiedUTC).ToString());
VB.NET results.Append("The Date Last Modified (UTC) " + _
"of this upload is: " + _
fileUpload.DateLastModifiedUTC.ToString())


ExpirationDate

ExpirationDate Property

Object: SoftArtisans.FileUp
Syntax: ExpirationDate
Type: Date
Read/Write: Read Only
Description:

This property returns the expiration date of the current evaluation version. A full, non-evaluation version returns an empty expiration date.

Examples:
ASP The Expiration Date of FileUp is: <%=fileUpload.ExpirationDate%>.
C# results.Append("The Expiration Date of FileUp is: " +
((DateTime)fileUpload.ExpirationDate).ToString());
VB.NET results.Append("The Expiration Date of FileUp is: " + _
fileUpload.ExpirationDate.ToString())


Form

Form Collection

Object: SoftArtisans.FileUp
Syntax: Form(Form Element Name As String)
Type String
Read/Write: Read/Write
Description:

This property retrieves the value of the specified form element. It returns form values in the same format as the ASP Request.Form object with the exception of multi-select list boxes (<select multiple>) or check boxes. For multiselect list boxes, use the FormEx property.

If the form element is a file, it returns the location of the file on the server.

Form Element Name is an optional parameter.

There is one difference between the FileUp form object and the ASP Request.Form: It is possible to retrieve the raw unparsed form by specifying Request.Form without any parameters. This is acceptable when the form is small, such as less than 100 KB. However, in the case of file uploads, the potential size of the data is very large. By design, FileUpdoes not place the entire contents of files into memory. Thus, FileUp.Form will not return the unparsed data.

FileUp allows uploads into memory. See the UseMemory Property .

If you require access to the unparsed data, you can use the SaveBinaryAs method and then read back appropriate sections using SA-FileManager.
Examples:

Looping through the members of Form:

ASP <%
For Each x In fileUpload.Form
Response.Write(x & ": " & fileUpload.Form(x) & "<br />")
Next
%>
C# foreach (object x in fileUpload.Form)
{
results.Append(x + ": " + fileUpload.Form[x] + "<br />")
}
VB.NET For Each (x As Object In fileUpload.Form)
results.Append(x & ": " + fileUpload.Form(x) & "<br />")
Next

For a complete discussion and code samples demonstrating the use of the Form and FormEx properties in regards to file input, single text input and multiselect controls, please see:

  • Programmer's Guide for ASP: Accessing Multiple Form Elements
  • Programmer's Guide for ASP.NET: Accessing Multiple Form Elements


FormEx

FormEx Collection

Object: SoftArtisans.FileUp
Syntax: FormEx(Form Element Name As String)
Type: String or file object, depending on file contents
Read/Write: Read/Write
Description:

This property retrieves the values of collections. It returns a collection. To access the elements of a FormEx collection, use either:

  • A "For...Each" statement. For example: "For Each item In fileUpload.FormEx(multipart)"

    OR

  • Index numbers (1-based). For example: "fileUpload.FormEx("name").Index"

If the form element is a file, FormEx will return the location of the file on the server (see the ServerName property).

There is a difference between the FileUp FormEx object and the ASP Request.Form: It is possible to retrieve the raw unparsed form by specifying Request.Form without any parameters. This is acceptable when the form is small, such as less than 100 KB. However, in the case of file uploads, the potential size of the data is very large. By design, FileUpdoes not place the entire contents of files into memory. In summary, FileUp.FormEx will not return the unparsed data.

FileUp allows uploads into memory. See the UseMemory Property .

If you require access to the unparsed data, it is possible to use the SaveBinaryAs method and then read back appropriate sections using SA-FileManager.

Examples:

Looping through the members of FormEx:

ASP <%
'--- It's a subcollection, we'll need to loop again
'--- to retrieve the values of the subcollection here
'--- Note how we need to use FormEx to determine if it's a
'--- subcollection always use FormEx when using, or if
'--- anticipating using, subcollections!
If fileUpload.FormEx(strFormElement).Count > 1 Then

Response.Write "Subcollection: " & strFormElement & "<br />"
i = 1

'--- Loop through the subcollection
For Each strSubItem In fileUpload.FormEx(strFormElement)
Response.Write i & ": " & strSubItem & "<br />"
i = i + 1
Next
Response.Write "<br /><br />"

Else

'--- It's just a single value, not a subcollection
'--- simply display the single value
Response.Write "Form single value: " & strFormElement & _
fileUpload.Form(strFormElement) & "<br />"

End If
%>
C# //--- It's a subcollection, we'll need to loop again
//--- to retrieve the values of the subcollection here
//--- Note how we need to use FormEx to determine if it's a
//--- subcollection always use FormEx when using, or if
//--- anticipating using, subcollections!
if (fileUpload.FormEx[strFormElement].Count > 1)
{
Response.Write("Subcollection: " + strFormElement + "<br />");
i = 1;

//--- Loop through the subcollection
foreach (object subItem in fileUpload.FormEx[strFormElement])
{
Response.Write(i + ": " + subItem + "<br />");
i = i + 1;
}

Response.Write("<br /><br />");
}
else
{
//--- It's just a single value, not a subcollection
//--- simply display the single value
Response.Write("Form single value: " + strFormElement +
fileUpload.Form[strFormElement] + "<br />");
}
VB.NET '--- It's a subcollection, we'll need to loop again
'--- to retrieve the values of the subcollection here
'--- Note how we need to use FormEx to determine if it's a subcollection
'--- always use FormEx when using, or if anticipating using, subcollections!
If (fileUpload.FormEx(strFormElement).Count > 1) Then

Response.Write("Subcollection:" + strFormElement + "<br />")
i = 1

'--- Loop through the subcollection
For Each (subItem As Object In fileUpload.FormEx(strFormElement))

Response.Write(i + ": " + subItem + "<br />")
i = i + 1

Next

Response.Write("<br /><br />")

Else

'--- It's just a single value, not a subcollection
'--- simply display the single value
Response.Write("Form single value: " & strFormElement &
fileUpload.Form(strFormElement) & "<br />")

End Try

For a complete discussion and code samples demonstrating the use of the Form and FormEx properties in regards to file input, single text input and multiselect controls, please see:

  • Programmer's Guide for ASP: Accessing Multiple Form Elements
  • Programmer's Guide for ASP.NET: Accessing Multiple Form Elements


IsEmpty

IsEmpty Property

Object: SoftArtisans.FileUp
Syntax: IsEmpty
Type: Boolean
Read/Write: Read Only
Description:

This property displays whether the user specified a valid file to upload.

When a user is filling out a form containing a file (<input type="file" />), there are three possibilities:

  1. The user specifies a valid filename on the local PC.
  2. The user leaves the filename field blank, decides not to transmit a file, but presses the submit button anyway.
  3. The user specifies a filename that is either invalid or indicates a file that is unreadable.

In the second and third cases, the browser does not report an error. The browser simply proceeds with the upload but leaves the file contents of the upload empty.

Your recourse is to let the user perform the upload and test the IsEmpty property.

If the property is True, the user did not transmit a valid file.

If the property is False, the user did transmit a valid file.

If there is more than one file being uploaded in a single page, only the first one is displayed.

To examine the IsEmpty property of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("File1").IsEmpty. See SAFile.IsEmpty.

Examples:
ASP <% If fileUpload.IsEmpty Then %>
The file that you uploaded was empty. Most likely, you did not
specify a valid filename to your browser or you left the
filename field blank. Please try again.
<% Else >
'--- Process upload
< End If %>
C# if (fileUpload.IsEmpty)
{
results.Append("The file that you uploaded was empty. Most " +
"likely you did not specify a valid filename to your " +
"browser or you left the filename field blank. " +
"Please try again."); }
else
{
//--- Process upload
}
VB.NET If (fileUpload.IsEmpty) Then

results.Append("The file that you uploaded was empty. Most " + _
"likely you did not specify a valid filename to your browser " + _
"browser or you left the filename field blank. " + _
"Please try again.");
Else

'--- Process upload

End If


Item

Item Property

Object: SoftArtisans.FileUp
Syntax: Item
Type: String or a SA-File object
Read/Write: Read/Write
Description:

This property is a shortened notation equivalent to Form("key").

This is the default property of FileUp and is used to maintain compatibility with the ASP Request object. In the context of a Post, Request("key") is equivalent to Request.Form("key").

Similarly, with FileUp,fileUpload("key") is equivalent to fileUpload.Form("key"). It is the Item property that allows this to occur.


MaxBytes

MaxBytes Property

Object: SoftArtisans.FileUp
Syntax: MaxBytes
Type: Long Integer
Read/Write: Read/Write
Description:

This property defines the maximum number of bytes that are written to disk or into the database on a per-filebasis.

This important property prevents malicious users from filling your web server's hard disk.

If a user uploads a file larger than MaxBytes, no error is reported. Instead, writing stops at exactly that value. For example, if MaxBytes is set to 200, and the user uploads a file that is 300 bytes long, only the first 200 bytes are written to the web server's hard disk.

Each individual file in the upload has this limit. For example, if there are three files in a single form and MaxBytes is set to 500:

File | Original Size | Written Size
file1 | 1000 | 500
file2 | 200 | 200
file3 | 600 | 500

Setting MaxBytes to zero (0) implies no limit. This is the default value.

You can also use MaxBytes in conjunction with the SaveBinaryAs method .

Note: When using the HttpModule with an ASP.NET upload, use the MaxBytes registry key instead of this property. Since the HttpModule is used for caching, this property will not affect the uploaded file.

For discussion and code samples on limiting the upload size, please see:

  • Programmer's Guide for ASP: Limiting the Upload Size
  • Programmer's Guide for ASP.NET: Limiting the Upload Size

See also, MaxBytesToCancel.

Examples:
ASP <%
fileUpload.MaxBytes = 300000
fileUpload.SaveAs filename
%>
ASP.NET N/A - Use MaxBytes registry key.


MaxBytesToCancel

MaxBytesToCancel Property

Object: SoftArtisans.FileUp
Syntax: MaxBytesToCancel
Type: Long
Read/Write: Read/Write
Description:

FileUp will abort a file transfer to the server when the size of the transfer reaches the value of MaxBytesToCancel. No data will be written to the server's hard disk, the connection will be terminated, and the browser will display a "Page not found" message.

Setting MaxBytesToCancel may reduce the threat of a DoS (Denial of Service) attack on the server. When an upload size hits MaxBytesToCancel, the connection to the server will be terminated, the ASP page will finish executing, and the ASP thread will be freed.

Each concurrent upload occupies one ASP thread. ASP typically allows simultaneous execution of a maximum of 25 threads per processor. To reduce the risk of a DoS, in addition to setting MaxBytesToCancel, increase the value of ProcessThreadMax, and/or add additional processors.

The unit of MaxBytesToCancel is a byte. The default value of MaxBytesToCancel is 0, that is, the property is disabled by default.

MaxBytesToCancel must be set before any form elements are referenced, which would force the upload request to be cached. Because MaxBytesToCancel must be set before the request is cached, in ASP.NET, this value must be set as a registry key to make the value available to the HttpModule. Please see: FileUp Registry Keys.

Note: MaxBytesToCancel is available with IIS4 or higher.

Note: When using the HttpModule with an ASP.NET upload, use the MaxBytesToCancel registry key instead of this property. Since the HttpModule is used for caching, this property will not affect the uploaded file.

For discussion and code samples on limiting the upload size, please see:

  • Programmer's Guide for ASP: Limiting the Upload Size
  • Programmer's Guide for ASP.NET: Limiting the Upload Size

See also, MaxBytes.

Examples:
ASP <%
fileUpload.MaxBytesToCancel = 50000000
%>
ASP.NET N/A - Use MaxBytesToCancel registry key.


MimeVersion

MimeVersion Property

Object: SoftArtisans.FileUp
Syntax: MimeVersion
Type: String
Read/Write: Read Only
Description:

This is typically left blank by both Microsoft and Netscape browsers but may contain the MIME version.

If there is more than one file being uploaded in a single page, only the first one is displayed.

To examine the MIME version of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("File1").MimeVersion.

Examples:
ASP The MIME Version of the first file uploaded is: <%=fileUpload.MimeVersion%>.
C# results.Append("The MIME Version of the first file uploaded " +
"is: " + fileUpload.MimeVersion);
VB.NET results.Append("The MIME Version of the first file uploaded is: " + _
fileUpload.MimeVersion)


OverWriteFiles

OverWriteFiles Property

Object: SoftArtisans.FileUp
Syntax: OverWriteFiles
Type: Boolean
Read/Write: Read/Write
Description:

This property determines if an upload will overwrite an existing file on the server.

Note: By default, this property is True, so files will be over-written.

If this property is set to false, the following error will be raised at run-time when a file that already exists on the server is uploaded again:

Error: 183 ... Cannot create a file when that file already exists. (SoftArtisans.SAFile.1)

The above error can be handled and/or the CreateNewFile property can be used to generate a new, unique filename.

This property must be set before the upload is cached. In ASP, this means that the value must be set before referencing any form elements.

Note: When using the HttpModule with an ASP.NET upload, since the HttpModule caches the upload before FileUp is instantiated, this property will have no effect.
Examples:
ASP <%
'--- Create an instance of SoftArtisans FileUp
Set fileUpload = Server.CreateObject(SoftArtisans.FileUp)

'--- Set the default path to store uploaded files
fileUpload.Path = "C:\temp"

'--- Set OverWriteFiles to False
fileUpload.OverWriteFiles = False
%>
ASP.NET N/A


Path

Path Property

Object: SoftArtisans.FileUp
Syntax: Path[=Physical Path As String]
Type: String
Read/Write: Read/Write
Description:

This property defines the default directory for saving files. It also defines the default directory for caching files before a final save is executed in ASP, provided the property is set before any form elements or files are referenced in the script.

Note: In ASP.NET, when the FileUp HttpModule is implemented, the path property does not determine the caching location. Instead, the caching location must be set for the HttpModule, not the FileUp object. The path property, however, does still determine the default save location. (See: FileUp registry keys)

After determining the directory that will be used by the Path propery, you must also be certain to grant "read", "write" and "modify" NTFS permissions so that FileUp can cache or save to this location.

Setting the path property in ASP can improve performance in the following ways:

  • In ASP, the path property is checked to provide a location for caching. If a value is not provided, FileUp is forced to check other locations for a suitable directory.
  • When the FileUp object is responsible for caching (in ASP), if the path is not provided, it will attempt to cache to the location specified in your system TEMP variable, which is typically a location on the C: drive. In a typical webserver configuration, uploaded content will be saved to the D: drive or other volume. Moving the file across drives requires more system resources than moving the file to a different directory on the same drive.

In ASP, when the first upload reaches the server, FileUp will search for a writable Temp directory, and assign it to the Path property. FileUp will check the following: the TEMP environment variable, C:\Windows\Temp, C:\Winnt\Temp, C:\Temp, C:\tmp, and GetTempDir().

If FileUp does not find a writable Temp directory, and the Path property is not set in script, an error will occur. A Path assignment in script will overwrite FileUp's default Path value.

If you set Path, you can still save the file to a different location. When using the SaveAs method, specify a new complete path and file name. In this scenario, the upload is cached in the default path. When the SaveAs method is executed, the file is moved from the default path to the new destination. This works even if the new destination is on a different disk or on a network share.

Note: To change the system's default directory for cached files (the first directory FileUp will try to use as a default cache), reset the TEMP environment variable, as follows:
  • Open the Control Panel.
  • Select System.
  • Select the Advanced tab.
  • Click Environment variables...
  • Select TEMP from the System Variables list.
  • Click Edit.
  • Enter a new Variable Value, and click Ok.
Examples:

Cache and save the upload on the web server at C:\Uploads:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location to web server path
fileUpload.Path = "C:\Uploads"

'--- Save upload
fileUpload.Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default save location to web server path
//--- (Cache location is set using FileUpTempDir registry key) fileUpload.Path = @"C:\Uploads";

//--- Save upload
fileUpload.Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- Set default save location to web server path
'--- (Cache location is set using FileUpTempDir registry key) fileUpload.Path = "C:\Uploads"

'--- Save upload
fileUpload.Save()

Cache and save the upload to a network shared drive:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location to network share
fileUpload.Path = "\\FileServer\Uploads"

'--- Save upload
fileUpload.Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default save location to network share
//--- (Cache location is set using FileUpTempDir registry key)
fileUpload.Path = @"\\FileServer\Uploads";

//--- Save upload
fileUpload.Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- Set default save location to network share
'--- (Cache location is set using FileUpTempDir registry key)
fileUpload.Path = "\\FileServer\Uploads"

'--- Save upload
fileUpload.Save()

Cache the upload to the web server and save it to a network shared drive:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location to web server path
fileUpload.Path = "C:\Temp"

'--- Save upload to network share using original filename
fileUpload.SaveAs "\\FileServer\Uploads\" & _
fileUpload.form("File1").ShortFileName
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- (Cache location is set to C:\Temp using FileUpTempDir
//--- registry key)

//--- Save upload to network share using original filename
fileUpload.SaveAs(@"\\FileServer\Uploads\" +
fileUpload.form("File1").ShortFileName);
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- (Cache location is set to C:\Temp using FileUpTempDir
'--- registry key)

'--- Save upload to network share using original filename
fileUpload.SaveAs("\\FileServer\Uploads\" + _
fileUpload.form("File1").ShortFileName)


PerConnectionBandwidthLimit

PerConnectionBandwidthLimit Property

Object: SoftArtisans.FileUp
Syntax: PerConnectionBandwidthLimit[= Kilobytes As Long]
Type: Long
Read/Write: Read/Write
Description:

This property, when used in conjunction with the TransferFile method for downloads, will limit each connection to a specific bandwidth.

If PerConnectionBandwidthLimit is set, each individual download will not exceed the designated speed. By default, PerConnectionBandwidthLimit is set to 0, meaning no effect. This property is set in kilobytes.

Note: PerConnectionBandwidthLimit is implemented on NT4 with IIS4 or higher, and Windows 2000.
Examples:
ASP <%
'--- Create an instance of SoftArtisans FileUp
Set fileDownload = Server.CreateObject(SoftArtisans.FileUp)

'--- Set bandwidth limit to 10 KB per connection
fileDownload.PerConnectionBandwidthLimit = 10

'--- Start the download
fileDownload.TransferFile "C:\MyServerDir\filename.doc"
%>
C# //--- Create an instance of SoftArtisans FileUp
FileUp fileDownload = new FileUp(Context);

//--- Set bandwidth limit to 10 KB per connection
fileDownload.PerConnectionBandwidthLimit = 10;

//--- Start the download
fileDownload.TransferFile("C:\MyServerDir\filename.doc");
VB.NET '--- Create an instance of SoftArtisans FileUp
Dim fileDownload As New FileUp(Context)

'--- Set bandwidth limit to 10 KB per connection
fileDownload.PerConnectionBandwidthLimit = 10

'--- Start the download
fileDownload.TransferFile("C:\MyServerDir\filename.doc")


PerServerBandwidthLimit

PerServerBandwidthLimit Property

Object: SoftArtisans.FileUp
Syntax: PerServerBandwidthLimit[= Kilobytes As Long]
Type: Long
Read/Write: Read/Write
Description:

This property, when used in conjunction with the TransferFile method for downloads, will limit the server-side total output to a specific bandwidth.

If PerServerBandwidthLimit is set, the total speed of the server's output for all connections combined will not exceed the designated limit. If this limit is exceeded, each connection will get a proportion of bandwidth based on the total bandwidth available, divided by the number of current connections. By default, PerServerBandwidthLimit is set to 0, meaning no effect. This property is set in kilobytes.

Note: PerServerBandwidthLimit is implemented on NT4 with IIS4 or higher, and Windows 2000.
Examples:
ASP <%
'--- Create an instance of SoftArtisans FileUp
Set fileDownload = Server.CreateObject(SoftArtisans.FileUp)

'--- Set the server-side bandwidth limit to
'--- 1000 KB for all connections combined
fileDownload.PerServerBandwidthLimit = 1000

'--- Start the download
fileDownload.TransferFile "C:\MyServerDir\filename.doc"
%>
C# //--- Create an instance of SoftArtisans FileUp
FileUp fileDownload = new FileUp(Context);

//--- Set the server-side bandwidth limit to
//--- 1000 KB for all connections combined
fileDownload.PerServerBandwidthLimit = 1000;

//--- Start the download
fileDownload.TransferFile("C:\MyServerDir\filename.doc");
VB.NET '--- Create an instance of SoftArtisans FileUp
Dim fileDownload As New FileUp(Context)

'--- Set the server-side bandwidth limit to
'--- 1000 KB for all connections combined
fileDownload.PerServerBandwidthLimit = 1000

'--- Start the download
fileDownload.TransferFile("C:\MyServerDir\filename.doc")


PreserveMacBinary

PreserveMacBinary Property

Object: SoftArtisans.FileUp
Syntax: PreserveMacBinary [=Boolean]
Type: Boolean
Read/Write: Read/Write
Description:

If PreserveMacBinary is set to true, FileUp will preserve both the data and resource forks from a properly formatted MacBinary upload. By default, PreserveMacBinary is set to false, meaning that FileUp will save only the data fork of the upload stream even if the resource fork is available. This property is only relevant when the upload is sent from the browser in MacBinary format.

PreserveMacBinary must be set before the upload is cached. In ASP, this means, set PreserveMacBinary before referencing any form elements.

Note: When using the HttpModule with an ASP.NET upload, since the HttpModule is used for caching, this property will have no effect.

Note: FileUp does not provide MacBinary encoding or decoding functionality; it merely preserves the forks if they are sent by the browser.

Examples:
ASP <%
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")
fileUpload.PreserveMacBinary = True
fileUpload.Path = "C:\Temp"
%>
ASP.NET N/A


ProgressID

ProgressID Property

Object: SoftArtisans.FileUp
Syntax: ProgressID[= ID As Integer]
Type: Integer
Read/Write: Read/Write
Description:

This property sets or gets the ID of the current upload. This lets you track the progress of the current upload.

To view the progress of a specific upload, you must assign a ProgressID to it. Then create a SoftArtisans.FileUpProgress object and use the same ProgressID. The FileUpProgress object has properties that update in real-time to reflect the current and total bytes to be uploaded.

To get the next unused ProgressID, use the NextProgressID method .

Pass the ProgressID from page to page in the query string or in a cookie. You cannot pass the ProgressID as a form value. The example in Adding a Server-Side Progress Indicator demonstrates passing the ProgressID in the query string.

The ID must be between 1 and 500. The ID is guaranteed to be unique at any one time, but it is not guaranteed to be unique for the duration of IIS's execution.

SoftArtisans assumes that Web servers will not use more than 500 simultaneous uploads. Since ASP has a fixed maximum number of concurrent pages that can be executed (25 in Windows 2000, 10 in IIS 4), even an 8-processor machine would handle a maximum of 200 uploads if all processors were totally dedicated to uploads. The maximum of 500 is easily changed, so if you have higher volume than this, please contact us .

Examples:

From the progress indicator sample:

ASP <%
'--- Assign the same progress ID that we assigned to the progress
'--- object
fileUpload.ProgressID = _
CInt(Request.QueryString("progressid"))
%>
C# //--- Get the progress id from the querystring
int intProgressID =
Convert.ToInt32(Request.QueryString["progressid"]);
fileUpload.ProgressID = intProgressID;
VB.NET Dim intProgressID As Integer = _
Convert.ToInt32(Request.QueryString("progressid"))
fileUpload.ProgressID = intProgressID

For a complete sample of progress indication including the use of the FileUp ProgressID property, see:

  • Programmer's Guide for ASP: Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator


ServerName

ServerName Property

Object: SoftArtisans.FileUp
Syntax: ServerName
Type: String
Read/Write: Read Only
Description:

This property displays the complete path and name of the uploaded file on the web server's hard disk.

Before a Save, SaveAs or SaveAsBlob is executed, the ServerName property contains the location and name of the temporary cache file used when processing uploads. After a Save, SaveAs or SaveAsBlob, ServerName displays the complete path and name of the final location of the file.

The cache filename is always guaranteed to be unique. You can use the .ServerName property to generate a unique name when saving the file. The cache file's name is of the form saNNNN.tmp, where NNNN is a unique number. See Example 2, below.

If there is more than one file being uploaded in a single page, only the first one is displayed.

To examine the Server Name of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.FormEx("FILE1").ServerName. Please see SAFile.ServerName
Examples:
ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location
fileUpload.Path = "C:\Temp"
filename = "upload.tst"
Response.Write("The uploaded file is now cached in: " & _
fileUpload.ServerName & "<br />")

Response.Write("Saving the file to: " & filename & "<br />")

On Error Resume Next

'--- Save upload
fileUpload.SaveAs filename

If Err = 0 Then
Response.Write("Upload saved successfully to: " & _
fileUpload.ServerName)
Else
'--- Handle errors
End If
%>

ServerName will display "C:\Temp\upload.tst"
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set cache/default save location
fileUpload.Path = @"C:\Temp";
filename = "upload.tst";

results.Append("The uploaded file is now cached in: " +
fileUpload.ServerName + "<br />");

results.Append("Saving the file to: " + filename + "<br />");

//--- Save upload
fileUpload.SaveAs(filename);

results.Append("Upload saved successfully to: " +
fileUpload.ServerName);

ServerName will display "C:\Temp\upload.tst"
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set cache/default save location
fileUpload.Path = "C:\Temp"
filename = "upload.tst"

results.Append("The uploaded file is now cached in: " + _
fileUpload.ServerName + "<br />")

results.Append("Saving the file to: " + filename + "<br />")

'--- Save upload
fileUpload.SaveAs(filename)

results.Append("Upload saved successfully to: " + _
fileUpload.ServerName)

ServerName will display "C:\Temp\upload.tst"


ShortFilename

ShortFilename Property

Object: SoftArtisans.FileUp
Syntax: ShortFilename
Type: String
Read/Write: Read Only
Description:

This property returns the user's original name for the uploaded file, not including any path information.

For example, if a user uploads a file from the following path on their hard drive: "C:\MyFiles\filename.txt", the ShortFilename property will return "filename.txt".

This property can be used in conjunction with the SaveAs or SaveInVirtualmethods to save a file with the user's original user's filename in a directory otherthan the one used to temporarily cache the uploaded files (stored in the Path property ). The Save method, on the other hand, will automatically save a file with the user's original filename to the directory assigned to the path property. Using SaveAs or SaveInVirtual in conjunction with ShortFilename is especially useful when you wish to dynamically set the destination of the upload based on data passed from the upload form.

This property is also useful for storing filenames in a database.

If there is more than one file being uploaded in a single page, only the first one is displayed.

To examine the ShortFilename of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("File1").ShortFilename.

See the ShortFilename property of the SAFile object.

Note: The ShortFilename property is only implemented on IIS4 or higher.
Examples:

Output filename to user:

ASP The file you uploaded was: <%=fileUpload.ShortFilename%>.
C# results.Append("The file you uploaded was: " +
fileUpload.ShortFilename);
VB.NET results.Append("The file you uploaded was: " + _
fileUpload.ShortFilename)

Save file using original filename to directory chosen by the user:

ASP <%
'--- Create an instance of SoftArtisans FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'---Set the default path to store uploaded files
fileUpload.Path = "C:\Temp"

'--- Retrieve the user's chosen directory from the form
Dim newPath
newPath = fileUpload.Form("Directory")

'--- Save the file with the user's original filename
'--- to the user's chosen directory
fileUpload.SaveAs newPath & "\" & fileUpload.ShortFilename
%>
C# //--- Create an instance of SoftArtisans FileUp
FileUp fileUpload As New FileUp(Context);

//---Set the default path to store uploaded files
fileUpload.Path = @"C:\Temp";

//--- Retrieve the user's chosen directory from the form
string newPath = fileUpload.Form("Directory");

//--- Save the file with the user's original filename
//--- to the user's chosen directory
fileUpload.SaveAs(newPath & "\\" & fileUpload.ShortFilename);
VB.NET '--- Create an instance of SoftArtisans FileUp
Dim fileUpload As New FileUp(Context)

'---Set the default path to store uploaded files
fileUpload.Path = "C:\Temp"

'--- Retrieve the user's chosen directory from the form
Dim newPath As String = fileUpload.Form("Directory")

'--- Save the file with the user's original filename
'--- to the user's chosen directory
fileUpload.SaveAs(newPath + "\" + fileUpload.ShortFilename)


TotalBytes

TotalBytes Property

Object: SoftArtisans.FileUp
Syntax: TotalBytes
Type: Long Integer
Read/Write: Read Only
Description:

This property displays the actual numbers of bytes written to disk.

The value of TotalBytes is always less than or equal to the MaxBytes property .

If there is more than one file being uploaded in a single page, only the first one is displayed.

To examine the Total Bytes written of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("FILE1").TotalBytes. Please see SAFile.TotalBytes
Examples:
ASP The Total Bytes of this upload is <%=fileUpload.TotalBytes%>.
C# results.Append("The Total Bytes of this upload is: " +
fileUpload.TotalBytes);
VB.NET results.Append("The Total Bytes of this upload is: " +
fileUpload.TotalBytes)


UseDateLastModified

UseLastDateModified Property

Object: SoftArtisans.FileUp
Syntax: UseDateLastModified
Type: Boolean
Read/Write: Read/Write
Description:

If the "X-Last-Modified" header is sent in a request, and FileUp's UseDateLastModifiedproperty is set to True, FileUp will preserve the last modification date of the file transmitted by the user.

Use one of the following properties to return the date:

  • FileUp.DateLastModified,
  • File.DateLastModified,
  • FileUp.DateLastModifiedUTC, and
  • File.DateLastModifiedUTC.

The file on the server will have the same creation and modification date as the user's original file. This only works if the client upload software sends this information.

Neither Netscape Navigator nor Microsoft Internet Explorer send the file's modification date. SoftArtisans XFile transmits this information by inserting the "X-Last-Modified" header in the Request, when XFile's [XFRequest].UseXLastModified property is set to True.

Sending the needed header:

If you are using a different upload client, use the following header to send the Last Modified date:

X-Last-Modified: Fri Dec 04 10:29:02 GMT 1998

Which can be defined as follows:

date-time = day date time 4DIGIT ; Dow Mmm dd hh:mm:ss zzz yyyy day = "Mon" /
            "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" date = month 2DIGIT ; month day month
            = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct"
            / "Nov" / "Dec" time = hour zone ; ANSI hour = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00
            - 23:59:59 zone = "UT" / "GMT" ; Universal Time

The file modification date is always sent in GMT format to account for time zone differences between the browser and server.

Examples:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location
fileUpload.Path = "C:\temp"

'--- Set UseLastDateModified to True
fileUpload.UseLastDateModified = True

'--- Save upload
fileUpload.Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set cache/default save location
fileUpload.Path = @"C:\temp";

//--- Set UseLastDateModified to true
fileUpload.UseLastDateModified = true;

//--- Save upload
fileUpload.Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- Set cache/default save location
fileUpload.Path = "C:\temp"

'--- Set UseLastDateModified to True
fileUpload.UseLastDateModified = True

'--- Save upload
fileUpload.Save()


UseIE5Fix

UseIE5Fix Property

Object: SoftArtisans.FileUp
Syntax: UseIE5Fix[= Boolean]
Type: Boolean
Read/Write: Read/Write
Description:

This property is a workaround for an Internet Explorer 5 behavior.

The UseIE5Fix property will prevent the unintentional duplication of form data which can be generated by certain versions of Internet Explorer 5, when a user enters special characters into form fields. UseIE5Fix is set to TRUE by default. This will result in duplicate values being eliminated. If the user will need to intentionally produce duplicate values, set this property to FALSE.

Note: UseIE5Fix is implemented on NT4 with IIS4 or higher, and Windows 2000.
Examples:
ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location
fileUpload.Path = "C:\temp"

'--- Disable the UseIE5Fix property to allow duplicate form values
fileUpload.UseIE5Fix = False

'--- Save upload
fileUpload.Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set cache/default save location
fileUpload.Path = @"C:\temp";

//--- Disable the UseIE5Fix property to allow duplicate form values
fileUpload.UseIE5Fix = false;

//--- Save upload
fileUpload.Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- Set cache/default save location
fileUpload.Path = "C:\temp"

'--- Disable the UseIE5Fix property to allow duplicate form values
fileUpload.UseIE5Fix = False

'--- Save upload
fileUpload.Save()


UseMemory

UseMemory Property

Object: SoftArtisans.FileUp
Syntax: UseMemory[= Boolean]
Type: Boolean
Read/Write: Read/Write
Description:

If UseMemory is set to True, FileUp will store uploaded data in memory until it is saved. By default, UseMemory is set to False and FileUp will write uploaded data to temporary files before saving.

Storing an upload in memory is faster and more secure than storing on disk. However, before enabling UseMemory, consider other factors affecting the upload, such as how much memory is available on the server, how active the server is, and the size of the upload.

Note: When using the HttpModule with an ASP.NET upload, since the HttpModule caches the uploaded file before passing the request to FileUp, this property will have no effect.
Examples:
ASP <%
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")
fileUpload.UseMemory = True
%>
ASP.NET N/A


UserFilename

UserFilename Property

Object: SoftArtisans.FileUp
Syntax: UserFilename
Type: String
Read/Write: Read Only
Description:

This property contains the name on the user's hard disk, including path, of the file that was uploaded.

To extract the user's original filename from the complete path on the client machine, if necessary, use VBScript as in Example 2, below. Or (with version 3.3.2 and above of FileUp) use the ShortFilename property.

The complete name of the file depends on the user's operating system. If user uploads from a Windows PC, the path will be the usual driveletter:\dir1\dir2\file.ext. Several customers have reported that certain browsers on Macintoshes do not report valid pathnames. We have been unable to verify this.

UNIX users will send files in driveletter:\dir1\\file.ext format.

If there is more than one file being uploaded in a single page, only the first one is displayed.

To examine the UserFilename of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("File1").UserFilename. Please see SAFile.UserFileName
Examples:

Output entire client file name (including path) of the first uploaded file:

ASP The file you uploaded was: <%=fileUpload.UserFilename%>.
C# results.Append("The file you uploaded was: " +
fileUpload.UserFilename);
VB.NET results.Append("The file you uploaded was: " + _
fileUpload.UserFilename)


Version

Version Property

Object: SoftArtisans.FileUp
Syntax: Version
Type: String
Read/Write: Read Only
Description: This property returns the current version number of FileUp. This value is the same value as the version of the "safileup.dll" file.
Examples:
ASP Version of FileUp: <%=fileUpload.Version%>.
C# | results.Append("Version of FileUp: " & fileUpload.Version);
VB.NET | results.Append("Version of FileUp: " + fileUpload.Version)


SAFile Object

The SAFile object object represents a single uploaded file. It contains various methods and properties that let you manipulate the upload.

An instance of the SAFile object is automatically created by the principal FileUp object when an upload is in progress. You can create an instance of the SAFile object independently so that you can access several of its general-purpose functions, even if there is no upload in progress.

To instantiate and use the SAFile object in ASP:

ASP <%
'--- Create a new SAFile object Dim file
Set file = Server.CreateObject("SoftArtisans.SAFile")
%>
ASP <%
'--- Get an existing SAFile object from an upload Dim file
Set file = fileUpload.Form("MyFile1")
%>

In ASP.NET it is not possible to instantiate a new SAFile object. You can only get an existing SAFile object from the Form collection of an upload.

(ASP.NET samples assume the inclusion of the SoftArtisans.Net namespace.)

C# | SaFile file = (SaFile)fileUpload.Form["MyFile"];
VB.NET | Dim file As SaFile = CType(fileUpload.Form("MyFile"), SaFile)

After that, all methods and properties are available to you.

SAFile Methods

SAFile Properties


SAFile Object Methods

This section contains the methods implemented by the SAFile object.

Create Method

CreateTemp Method

Delete Method

Save Method

SaveAs Method

SaveAsBlob Method

SaveInVirtual Method


Delete

Delete Method

Object: SoftArtisans.SAFile
Syntax: Delete([in,optional] Filename As String)
Description:

This method deletes a file from the web server's hard disk.

If you specify a filename, it must contain the entire valid path.

If you do not specify a filename, the current uploaded file is deleted. This effectively allows you to cancel an upload.

See also the Delete method for the SAFileUp object.

Examples:

Delete an uploaded file that was saved to disk:

ASP <%
fileUpload.Path = "C:\MySaveLocation"
Set file = fileUpload.Form("MyFile1")

'--- Save the file to C:\MySaveLocation
file.Save

'--- Delete the file that you just saved.
file.Delete
%>
C# fileUpload.Path = @"C:\MySaveLocation";
SaFile file = (SaFile)fileUpload.Form["MyFile1"];

//--- Save the file to C:\MySaveLocation
file.Save();

//--- Delete the file that you just saved
file.Delete();
VB.NET fileUpload.Path = "C:\MySaveLocation"
Dim file As SaFile = CType(fileUpload.Form("MyFile1"), SaFile)

'--- Save the file to C:\MySaveLocation
file.Save()

'--- Delete the file that you just saved
file.Delete()

Delete uploads that are not gifs or jpegs:

ASP <%
Set file = fileUpload.Form("myFile");

strContentType = fileUpload.ContentType

If (strContentType = "image/gif") Then

file.Save

ElseIf (strContentType = "image/pjpeg") Then

file.Save

Else

file.Delete

End If
C# SaFile file = (SaFile)fileUpload.Form["myFile"];

String strContentType;
strContentType = fileUpload.ContentType;

switch(strContentType)
{
case "image/gif":
file.Save();
break;
case "image/pjpeg":
file.Save();
break;
default:
file.Delete();
break;
}
VB.NET Dim file As SaFile
file = CType(fileUpload.Form("myFile"), SaFile)

Dim strContentType as String
strContentType = file.ContentType

Select Case strContentType
Case "image/gif"
file.Save
Case "image/pjpeg"
file.Save
Case Else
file.Delete
End Select


Save

Save Method

Object: SoftArtisans.SAFile
Syntax: Save()
Description:

This method saves an uploaded file to the Web server's hard disk using the user's original filename.

When you use the Save method, you must also use the Path property to set the path.

See also the Save method for the SAFileUp object.

Examples:

The following saves the uploaded file from form element "Form1" on the Web server at C:\Uploads:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload at C:\Uploads
fileUpload.Path = "C:\Uploads"

'--- Save upload at C:\Uploads
fileUpload.Form("File1").Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default Save location to C:\Uploads
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = "C:\\Uploads";

//--- Save upload to C:\Uploads
fileUpload.Form["File1"].Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set default Save location to C:\Uploads
'--- (Cache location is set in registry since HttpModule is used
'--- with .NET)
fileUpload.Path = "C:\Uploads"

'--- Save upload to C:\Uploads
fileUpload.Form("File1").Save()

The following saves the uploaded file from form element "File1" to a network shared drive:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload at \\FileServer\Uploads
fileUpload.Path = "\\FileServer\Uploads"

'--- Save upload to \\FileServer\Uploads
fileUpload.Form("File1").Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default Save location to \\FileServer\Uploads
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = @"\\FileServer\Uploads";

//--- Save upload to \\FileServer\Uploads
fileUpload.Form["File1"].Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set default Save location to \\FileServer\Uploads
'--- (Cache location is set in registry since HttpModule is used
'--- with .NET)
fileUpload.Path = "\\FileServer\Uploads"

'--- Save upload to \\FileServer\Uploads
fileUpload.Form("File1").Save()

The following snippet taken from the "SaveAllInLoop" sample, demonstrates the checks neccessary to avoid errors when calling the Save method on a file:

ASP <%
If IsObject(fileUpload.Form(strFormElement)) Then

'--- It's a file element,
'--- so we'll see if it's empty or not
If Not fileUpload.Form(strFormElement).IsEmpty Then

'--- It's not empty, so we'll save it
fileUpload.Form(strFormElement).Save

Response.Write "<td>File</td><td>" &_
"strFormElement & </td><td>Saved as: " & _
fileUpload.Form(strFormElement).ServerName & _
"</td>"

End If

End If
%>
C# //--- If it's a SaFile object, it's a file
if(oFormExItem[1] is SaFile)
{
SaFile file = (SaFile)oFormExItem[1];

//--- Check to be sure the file element isn't empty
if(!file.IsEmpty)
{
//--- It's not empty, so we'll save it
file.Save();

results.Append("<td>File</td><td>" +
item.ToString() +
"</td><td>Saved as: " +
file.ServerName + "</td>");
}
else
{
//--- It's empty, just write a message
results.Append("<td>File</td><TD>" +
item.ToString() &
"</td>" + "<td>(empty)</td>");
}
}
VB.NET '--- If it's a SaFile object, it's a file
If (oFormExItem(1).GetType() Is GetType(SaFile)) Then

Dim file As SaFile = CType(oFormExItem(1), SaFile)

'--- Check to be sure the file element isn't empty
If Not (file.IsEmpty) Then

'--- It's not empty, so we'll save it
file.Save()

results.Append("<td>File</td><td>" +_
item.ToString() + "</td><TD>Saved as: " + _
file.ServerName + "</td>")

Else

'--- It's empty, just write a message
results.Append("<TD>File</td><td>" +_
item.ToString() + "</td>" + _
"<td>(empty)</td>")
End If

'--- If it's "string", it's just a standard
'--- form element
ElseIf(oFormExItem(1).GetType() Is GetType(String)) Then

results.Append("<td>Form single value</td><td>" +_
item.ToString() + "</td><td>" + _
oFormExItem(1).ToString() + "</td>")

End If


SaveAs

SaveAs Method

Object: SoftArtisans.SAFile
Syntax: SaveAs([in] Filename As String)
Description:

This method saves an uploaded file to the web server's hard disk.

SaveAs takes a physical path for its Filename argument. This can be provided in one of two ways:

  • Provide a complete physical path and file name.
  • Provide only a name for the file. SaveAs will take the directory path from the Path property.

See also the SaveAs method for the SAFileUp object.

Examples:

The following sets the Path property to C:\Temp and saves the uploaded file from form element "File1" on the Web server at C:\Uploads:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload to C:\Temp
fileUpload.Path = "C:\Temp"

'--- Save upload to C:\Uploads using the original filename of the file
fileUpload.Form("File1").SaveAs "C:\Uploads\" & fileUpload.Form("File1").ShortFileName
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default Save location to C:\Temp
//--- (Cache location is set in registry since HttpModule is used with .NET)
fileUpload.Path = "C:\\Temp";

//--- Save upload to C:\Uploads using the original filename of the file
fileUpload.Form["File1"].SaveAs("C:\\Uploads\\" + fileUpload.Form("File1").ShortFileName);
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- Set default Save location to C:\Temp
'--- (Cache location is set in registry since HttpModule is used with .NET)
fileUpload.Path = "C:\Temp"

'--- Save upload to C:\Uploads using the original filename of the file
fileUpload.Form("File1").SaveAs("C:\Uploads\" + fileUpload.Form("File1").ShortFileName)

The following sets the Path property to C:\Temp and saves the uploaded file from form element "File1" to a network shared drive:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Cache upload to C:\Temp
fileUpload.Path = "C:\Temp"

'--- Save upload to \\FileServer\Uploads using the original filename of the
'--- file
fileUpload.Form("File1").SaveAs "\\FileServer\Uploads" & _
fileUpload.Form("File1").ShortFileName
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default Save location to C:\Temp
//--- (Cache location is set in registry since HttpModule is used
//--- with .NET)
fileUpload.Path = "C:\\Temp";

//--- Save upload to \\FileServer\Uploads using the original filename of the
//--- file
fileUpload.Form["File1"].SaveAs("\\FileServer\Uploads\" +
fileUpload.form("File1").ShortFileName);
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set default Save location to C:\Temp
'--- (Cache location is set in registry since HttpModule is used
'--- with .NET)
fileUpload.Path = "C:\Temp"

'--- Save upload to \\FileServer\Uploads using the original filename
'--- of the file
fileUpload.Form("File1").SaveAs("\\FileServer\Uploads\" + _
fileUpload.form("File1").ShortFileName)

The following demonstrates the checks that should be made on a file before calling SaveAs:

ASP <%
If IsObject(fileUpload.Form(strFormElement)) Then

'--- It's a file element,
'--- so we'll see if it's empty or not
If Not fileUpload.Form(strFormElement).IsEmpty Then

'--- It's not empty, so we'll save it
strPath = "c:\SaveLocation\myfirstfile.txt"
fileUpload.Form(strFormElement).SaveAs(strPath)
End If
End If
%>
C# if(file1 != null)
{
if(!file1.IsEmpty)
{
file1.SaveAs("C:\\SaveLocation\\myfirstfile.txt");
}
}
VB.NET If Not (file1 Is Nothing) Then
If Not (file1.IsEmpty) Then

file1.SaveAs("c:\SaveLocation\myfirstfile.txt")
End If
End If


SaveAsBlob

SaveAsBlob Method

Object: SoftArtisans.SAFile
Syntax: SaveAsBlob([in] ADOField)
Description:

This method saves an uploaded file to a database.

The ADOField argument must point to a valid ADO Field object that supports the AppendChunk method. Any OLEDB provider that supports the AppendChunk method can be the destination of a SaveAsBlob. FileUpuses late binding to find the AppendChunk method of the recordset member and writes the data using this method. Note that even char and varchar type fields support AppendChunk, although the size is significantly limited.

For Microsoft SQL Server, the column should be of 'image' or 'text' type. This distribution includes a sample SQL script that you can use to create tables for use in uploading files. See the Setup Instructions for uploading to a database on the server.

For Microsoft Access, the column should be 'OLE Object'. You can use the sample Access database included with this distribution (in the Samples directory) for downloading and uploading files.

When writing to BLOB (Binary Large OBject) fields, the ADO Recordset's cursor type must be adOpenDynamic (i.e., 2).

Any size limitations of the BLOB are imposed by the database.

The uploaded data is stored exactly as sent, with no interpretation.

If there is more than one file being uploaded in a single page, only the first one is saved.

To save multiple files in a single upload, there is an equivalent method for each file object, i.e., fileUpload.FormEx("File1").SaveAsBlob rs("FileCol").

See also the SaveAsBlob method for the SAFileUp object.

Performance Considerations When Uploading to a Database

In general, uploading to a database instead of a file is less efficient, both in terms of disk space and processor time. Due to the caching necessary when processing multiple form and file elements, the upload is saved to a file and then imported into the database. The temporary cache file is then deleted. Uploading to a database also consumes significant memory resources. It is possible that you will get errors such as the following when uploading to a database:

"There is insufficient system memory to run this query."

Uploading to a database is best when there are many small files that you wish to catalogue, such as small graphic images. Large uploads are generally best stored in native files.

See Also: ADO.NET and SaveAsBlob
Example:
ASP <%
Set rsBlob = Server.CreateObject("ADODB.Recordset")
rsBlob.Open "SimpleBlobTable", "AccessUpload", 2, 3

'---
'--- Add new record and update
'---
rsBlob.AddNew
fileUpload.Form("File1").SaveAsBlob rsBlob.Fields("FileCol")

rsBlob.Update
rsBlob.Close
Set rsBlob = Nothing
'...
%>


SaveInVirtual

SaveInVirtual Method

Object: SoftArtisans.SAFile
Syntax: SaveInVirtual([in] VirtualLocation As String)
Description:

This method saves an uploaded file to the web server's hard disk in a location specified by the virtual directory or filename in a virtual directory.

SaveInVirtual uses the ASP or ASP.NET Server.MapPath() function internally. The virtual directory is then mapped to a physical directory for FileUp to use. You must be certain that the physical directory to which the virtual path maps, has the correct NTFS permissions to save the file. For more information on these permissions, please see the "Configuration and Application Planning" section this documentation set and read the permissions topics that apply to the language and configuration that you are using. As with the MapPath function, you specify either a virtual directory or a filename. If you specify a filename, it is resolved in the current virtual directory.

The Web Administrator can disable all other save methods except SaveInVirtual. This prevents the Web Developer from writing to non-virtual directory locations on the server. See Disabling FileUpfeatures .

If the upload destination folder is a virtual directory, a malicious user may be able to upload an infected file to the directory and launch it through the Web. To prevent this, use a folder that is not a virtual directory as the upload destination location.
Examples:

Specify a virtual directory, but keep the user's original filename:

ASP <%
fileUpload.Form("File1").SaveInVirtual "./Uploads"
%>
C# | fileUpload.Form["File1"].SaveInVirtual("./Uploads");
VB.NET | fileUpload.Form("File1").SaveInVirtual("./Uploads")

Specify a virtual directory that includes the file name:

ASP <%
fileUpload.Form("File1").SaveInVirtual "./Uploads/Myfile.ext"
%>
C# | fileUpload.Form["File1"].SaveInVirtual("./Uploads/Myfile.ext");
VB.NET | fileUpload.Form("File1").SaveInVirtual("./Uploads/Myfile.ext")


SAFile Object Properties

Checksum Property

ContentDisposition Property

ContentTransferEncoding Property

ContentType Property

DateLastModified Property

DateLastModifiedUTC Property

IsEmpty Property

MimeVersion Property

Path Property

ServerName Property

ShortFilename Property

TotalBytes Property

UploadContents Property

UserFilename Property


Checksum

Checksum Property

Object: SoftArtisans.SAFile
Syntax: Checksum
Type: String
Read/Write: Read Only
Description:

FileUp generates an MD5 hash of each uploaded file, after it is received on the server. The Checksum property returns a string representing the specified file's MD5 hash.

You can use this value to verify the integrity of the uploaded file, by comparing an MD5 hash generated on the client, and the MD5 hash generated by FileUp on the server.

Note: Note that FileUp generates an MD5 hash on the server, not the client. To verify data integrity, you will need a tool that can generate an MD5 hash on the client, such as SoftArtisans FileManager which is included free with FileUp.
See Also: FileManager Checksum Property
Examples:
ASP <%
'--- Instantiate the FileUp object
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")
'...

'--- Get the client-side hash submitted by the form
clientHash = fileUpload.Form("FileHash")

'--- Now, make a server-side hash with FileUp
serverHash = fileUpload.Form("MyFile").CheckSum

Response.Write("<b>Comparing hashes</b><br />")
Response.Write("<b>Client hash:</b> " & clientHash & "<br />")
Response.Write("<b>Server hash:</b> " & serverHash & "<br />")

'--- Compare them to verify file integrity
If StrComp(clientHash, serverHash) = 0 Then
'--- The hashes are the same! File integrity is verified
fileUpload.Form("MyFile").Save
Response.Write("... Hashes <b>OK!</b><hr noshade="noshade" />")
Response.Write("File integrity has been verified, " & _
"and the file has been saved to: " &_
fileUpload.Form("MyFile").ServerName & "<br />")
Else
Response.Write("... Hashes <B>mismatch!</B>" & _
"<hr noshade="noshade" />")
Response.Write("File integrity cannot be verified " & _
"and will not be saved.")
End If
'...
%>
C# //--- Process the upload
private void ProcessUpload()
{
//--- Declare an object for FileUp
FileUp fileUpload = null;

//--- This StringBuilder will be used to display results
System.Text.StringBuilder res = new System.Text.StringBuilder();

try
{
//--- Instantiate the FileUp object
fileUpload = new FileUp(Context);

//--- When the HttpModule is used, the path property does not
//--- affect caching location. Instead it is merely used
//--- as a placeholder to store the path to the directory
//--- where the files will be saved.
fileUpload.Path = "C:\\UploadDir";

//--- Get a reference to the uploaded file field
SaFile file = (SaFile)fileUpload.Form["MyFile"];

//--- Check to be sure there was a file selected in the form
//--- If so, continue processing
if (file != null)
{
if (!file.IsEmpty)
{
//--- Get the client-side hash submitted by the form
string clientHash = &
fileUpload.Form["FileHash"].ToString();

//--- Now, make a server-side hash with FileUp
string serverHash = file.Checksum;

res.Append("Comparing hashes<br />");
res.Append("Client hash: " + clientHash + "<br />");
res.Append("Server hash: " + serverHash + "<br />");

//--- Compare them to verify file integrity
if (String.Compare(clientHash, serverHash) == 0)
{
//--- File integrity is verified
file.Save();
res.Append ("... Hashes OK!");
res.Append ("File integrity has been verified, " +
"and the file has been saved to: " +
file.ServerName + "<br />");
}
else
{
//--- If the hashes don't match, don't save the file
//--- Explicitly delete it
file.Delete();
res.Append ("... Hashes mismatch!");
res.Append ("File integrity cannot be verified " +
"and therefore it will not be saved.");
}

}
else
{
//--- If IsEmpty is true, the file field was left empty
res.Append ("There was no file submitted for upload.");
}
}
else
{
res.Append ("The referenced field does not exist " +
"or is not of type=\"file\"");
}

//--- Display the results on the webform
ltrUploadResults.Text = results.ToString();

}
catch(Exception ex)
{
//--- If an exception is caught, display the details
ltrUploadResults.Text = "An error has occurred:<br />" +
ex.Message;
}
finally
{
//--- Always call FileUp.Dispose in the finally block
if (fileUpload != null)
{
fileUpload.Dispose();
fileUpload = null;
}
}
}
VB.NET '--- Process the upload
Private Sub ProcessUpload()

'--- Declare an object for FileUp
Dim fileUpload as FileUp

'--- This StringBuilder will be used to display results
Dim res As New System.Text.StringBuilder()

Try

'--- Instantiate FileUp
fileUpload = New FileUp(Context)

'--- When the HttpModule is used, the path property does not
'--- affect caching location. Instead it is merely used
'--- as a placeholder to store the path to the directory
'--- where the files will be saved.
fileUpload.Path = "C:\UploadDir

'--- Get a reference to the uploaded file field
Dim file As SaFile = CType (fileUpload.Form("MyFile"), SaFile)

'--- Check to be sure there was a file selected in the form
'--- If so, continue processing
If Not (file Is Nothing) Then
If Not (file.IsEmpty) Then

'--- Get the client-side hash submitted by the form
Dim clientHash As String
clientHash = fileUpload.Form("FileHash").ToString()

'--- Now, make a server-side hash with FileUp
Dim serverHash As String = file.Checksum

res.Append("Comparing hashes<br />")
res.Append("Client hash: " + clientHash + "<br />")
res.Append("Server hash: " + serverHash + "<br />")

'--- Compare them to verify file integrity
If (String.Compare(clientHash, serverHash) = 0) Then

'--- File integrity is verified
file.Save()
res.Append ("... Hashes OK!")
res.Append ("File integrity has been verified, " + _
"and the file has been saved to: " + _
"file.ServerName + "<br />")
Else

'--- If the hashes don't match, don't save the file
'--- Explicitly delete it
file.Delete()
res.Append ("... Hashes mismatch!")
res.Append ("File integrity cannot be verified " + _
"and therefore it will not be saved.")
End If

Else
'--- If IsEmpty is true, the file field was left empty
res.Append("There was no file submitted for upload.")
End If

Else
results.Append ("The referenced field does not exist " + _
"or is not of type=""file""")
End If

'--- Display the results on the webform
ltrUploadResults.Text = res.ToString()

Catch ex As System.Exception
'--- If an exception is caught, display the details
ltrUploadResults.Text = "An error has occurred:<br />" + _
ex.Message
Finally
'--- Always call FileUp.Dispose in the finally block
If Not (fileUpload Is Nothing) Then
fileUpload.Dispose()
fileUpload = Nothing
End If

End Try

End Sub


ContentDisposition

ContentDisposition Property

Object: SoftArtisans.SAFile
Syntax: ContentDisposition
Type: String
Read/Write: Read Only
Description:

This property contains the MIME Content Disposition of the data, which should always be "form-data" when using a browser that supports RFC1867 uploads.

Use this property to determine whether the browser supports RFC1867.

Even if there are multiple files in an upload, each file's Content Disposition should still be "form-data".

To examine the content disposition of multiple files in a single upload, there is an equivalent property for each file object, i.e., fileUpload.Form("File1").ContentDisposition.

See also the ContentDisposition propertyfor the SAFileUp object.

Examples:
ASP <% If fileUpload.Form("File1").ContentDisposition <> "form-data" Then %>
Your first file upload did not succeed, most likely because your
browser does not support upload via this mechanism.
<% End If %>
C# if ((SaFile)fileUpload.Form["File1"]).ContentDisposition !=
"form-data")
{
results.Append("Your first file upload did not succeed, most " +
"likely because your browser does not support upload via " +
"this mechanism.");
}
VB.NET If (CType(fileUpload.Form("File1"), SaFile).ContentDisposition <> _    "form-data") Then
results.Append("Your first file upload did not succeed, " + _
"most likely because your browser does not support upload " + _
"viathis mechanism.")
End If


ContentTransferEncoding

ContentTransferEncoding Property

Object: SoftArtisans.SAFile
Syntax: ContentTransferEncoding
Type: String
Read/Write: Read Only
Description:

This property is typically blank, but may contain the MIME Content Transfer Encoding.

See also the ContentTransferEncoding property for the SAFileUp object.

Examples:
ASP The Content Transfer Encoding of the first uploaded file is:
<%=fileUpload.Form("File1").ContentTransferEncoding%>.
C# results.Append("The Content Transfer Encoding of the first uploaded file is: " +
((SaFile)fileUpload.Form["File1"]).ContentTransferEncoding);
VB.NET results.Append("The Content Transfer Encoding of the first uploaded file is: " + _
CType(fileUpload.Form("File1"), SaFile).ContentTransferEncoding)


ContentType

ContentType Property

Object: SoftArtisans.SAFile
Syntax: ContentType
Type: String
Read/Write: Read/Write
Description:

This property contains the MIME Content Type of the file, which is useful in determining the contents of the file.

It has been our experience that Netscape Navigator version 4 returns creative and diverse Content Types, depending on the file being uploaded. Internet Explorer typically returns the lowest common denominator that is "application/octet-stream".

See also the ContentType propertyfor the SAFileUp object.

Examples:
ASP <%
'--- Get the uploaded file's content-type and
'--- assign it to a variable.
strContentType = fileUpload.Form("MyFile").ContentType

'--- Use the Select Case Condition to restrict the file type.
Select Case LCase(strContentType)
Case "image/gif"
fileUpload.Form("MyFile").Save
Response.Write fileUpload.Form("MyFile").ShortFilename & _
" has been saved."

Case "image/pjpeg"
fileUpload.Save
Response.Write fileUpload.Form("MyFile").ShortFileName & _
" has been saved."

Case Else
fileUpload.Delete
Response.Write "You can only upload gif and jpeg files."
End Select
%>
C# String strContentType =
((SaFile)fileUpload.Form["MyFile"]).ContentType;

switch(strContentType)
{
case "image/gif":
file.Save();
break;
case "image/pjpeg":
file.Save();
break;
default:
file.Delete();
break;
}
VB.NET Dim strContentType As String = _
CType(fileUpload.Form("MyFile"), SaFile).ContentType

Select Case strContentType
Case "image/gif"
file.Save
Case "image/pjpeg"
file.Save
Case Else
file.Delete
End Select


DateLastModified

DateLastModified Property

Object: SoftArtisans.SAFile
Syntax: DateLastModified
Type: Date
Read/Write: Read Only
Description:

If UseDateLastModified is set to True, DateLastModified will return the last modification date of the file transmitted by the user. The date is displayed using the local time zone. To display the UTC date of the file, see the DateLastModifiedUTC property.

The DateLastModified property only works if the client-upload software sends this information. Neither Netscape Navigator nor Microsoft Internet Explorer send the file's modification date. SoftArtisans XFile transmits this information by inserting the "X-Last-Modified" header in the Request, when XFile's [XFRequest].UseXLastModified property is set to True.

Sending the needed header:

If you are using a different upload client, use the following header to send the Last Modified date:

date-time = day date time 4DIGIT ; Dow Mmm dd hh:mm:ss zzz yyyy day = "Mon" /
            "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" date = month 2DIGIT ; month day month
            = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct"
            / "Nov" / "Dec" time = hour zone ; ANSI hour = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00
            - 23:59:59 zone = "UT" / "GMT" ; Universal Time

The file modification date is always sent in GMT format to account for time zone differences between the browser and server.

See also: FileUp.DateLastModified.

Examples:

ASP The Date Last Modified of the first uploaded file is:
<%=fileUpload.Form("File1").DateLastModified%>.
C# results.Append("The Date Last Modified of the " +
"first uploaded file is: " +
((DateTime)((SaFile)fileUpload.Form
["File1"]).DateLastModified).ToString());
VB.NET results.Append("The Date Last Modified of the " + _
"first uploaded file is: " +
CType(CType(fileUpload.Form("File1"), _       SaFile).DateLastModified, DateTime).ToString())


DateLastModifiedUTC

DateLastModifiedUTC Property

Object: SoftArtisans.SAFile
Syntax: DateLastModifiedUTC
Type: Date
Read/Write: Read Only
Description:

If UseDateLastModified is set to True, DateLastModifiedUTC will return last modification date of the file transmitted by the user. The date is displayed using Universal Time (UTC, or GMT). For the local date of the file, see the DateLastModified property.

The DateLastModified property only works if the client-upload software sends this information. Neither Netscape Navigator nor Microsoft Internet Explorer send the file's modification date. SoftArtisans XFile transmits this information by inserting the "X-Last-Modified" header in the Request, when XFile's [XFRequest].UseXLastModified property is set to True.

Sending the needed header:

If you are using a different upload client, use the following header to send the Last Modified date:

date-time = day date time 4DIGIT ; Dow Mmm dd hh:mm:ss zzz yyyy day = "Mon" /
            "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" date = month 2DIGIT ; month day month
            = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct"
            / "Nov" / "Dec" time = hour zone ; ANSI hour = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00
            - 23:59:59 zone = "UT" / "GMT" ; Universal Time

The file modification date is always sent in GMT format to account for time zone differences between the browser and server.

Examples:

ASP The Date Last Modified (UTC) of the first uploaded file is:
<%=fileUpload.Form("File1").DateLastModifiedUTC%>.
C# results.Append("The Date Last Modified (UTC) " +
"of the first uploaded file is: " +
((DateTime)((SaFile)fileUpload.Form
["File1"]).DateLastModifiedUTC).ToString());
VB.NET results.Append("The Date Last Modified (UTC) " + _
"of the first uploaded file is: " + _
CType(CType(fileUpload.Form("File1"),_
SaFile).DateLastModifiedUTC), DateTime).ToString())


IsEmpty

IsEmpty Property

Object: SoftArtisans.SAFile
Syntax: IsEmpty
Type: Boolean
Read/Write: Read Only
Description:

This property indicates whether the user specified a valid file to upload.

When a user fills out a form containing a file (<input type="file" />), there are three possibilities:

  1. The user specifies a valid filename on the local PC.
  2. The user leaves the filename field blank, decides not to transmit a file, but presses the submit button anyway.
  3. The user specifies a filename that is either invalid or indicates a file that is unreadable.

In the second and third cases, the browser does not report an error. The browser simply proceeds with the upload but leaves the file contents of the upload empty.

Your recourse is to let the user perform the upload and test the IsEmpty property.

If the property is True, the user did not transmit a valid file.

If the property is False, the user did transmit a valid file.

See also the IsEmpty property for the SAFileUp object.

Examples:
ASP <%
'--- If the file does not exist, FileUp will
'--- throw an error when Save() is called.
If IsObject(fileUpload.Form("MyFile")) Then
If Not fileUpload.Form("MyFile").IsEmpty Then
fileUpload.Form("MyFile").Save
Else
Response.Write "There was no file submitted in the " & _          "form field."
End If
Else
Response.Write "The referenced field does not exist " & _
"or is not of type=""file"""
End If
%>
C# //--- Get a reference to the uploaded file field
SaFile file = (SaFile)fileUpload.Form["MyFile"];

//--- If the file does not exist, FileUp will
//--- throw an error when Save() is called.
if (file != null)
{
if (!file.IsEmpty)
{
file.Save();
}
}
VB.NET '--- Get a reference to the uploaded file field.
Dim file As SaFile = CType(fileUpload.Form("MyFile"), SaFile)

'--- If the file does not exist, FileUp will
'--- throw an error when Save() is called.

If Not (file Is Nothing) Then
If Not (file.IsEmpty) Then
file.Save()
End If
End If


MimeVersion

MimeVersion Property

Object: SoftArtisans.SAFile
Syntax: MimeVersion
Type: String
Read/Write: Read Only
Description:

This property is typically left blank by most browsers but may contain the MIME version.

Examples:
ASP The MIME Version of the first file uploaded is: <%=fileUpload.Form("File1").MimeVersion%>.
C# results.Append("The MIME Version of the first file uploaded is: " +
((SaFile)fileUpload.Form["File1"]).MimeVersion);
VB.NET results.Append("The MIME Version of the first file uploaded " + _
"is: " + CType(fileUpload.Form("File1"), SaFile).MimeVersion)


Path

Path Property

Object: SoftArtisans.SAFile
Syntax: Path[= Physical Path As String]
Type: String
Read/Write: Read/Write
Description:

This property, when used from the SAFile object defines the directory to which a file will be saved.

FileUpmust be able to write into this directory. Set permissions accordingly. For more information, please see the "Configuration and Application Planning" chapter.

It is important to distinguish between the Path property of the FileUp object and the Path property of the SAFile object. In ASP, or in ASP.NET when the HttpModule is not used, the Path property of the FileUp object is used as the location to cache the upload Request. To be used effectively, it must be set before any of the form elements are referenced. In ASP or in ASP.NET, the path property of the FileUp object is set to determine the default directory to be used for saving the files. Setting the path property of the SAFile object cannot affect caching location, but it can be used to change the default saving location on a per-file basis.

If no value is provided FileUpuses the system-defined Temporary Path (which is returned by the WIN32 GetTempPath() routine). Typically, this is "C:\Temp".

Examples:

Cache the upload on the web server at C:\Uploads and save the first uploaded file to C:\Uploads\MyFirstFile\.

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location to web server path
fileUpload.Path = "C:\Uploads"

'--- Set the default save location for the first file
fileUpload.Form("File1").Path = "C:\Uploads\MyFirstFile\"

'--- Save first uploaded file
fileUpload.Form("File1").Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set default save location to web server path
//--- (Cache location is set using FileUpTempDir registry key) fileUpload.Path = @"C:\Uploads";

//--- Set the default save location for the first file
((SaFile)fileUpload.Form["File1"]).Path =
@"C:\Uploads\MyFirstFile\";

//--- Save first uploaded file
((SaFile)fileUpload.Form["File1"]).Save();
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- Set default save location to web server path
'--- (Cache location is set using FileUpTempDir registry key) fileUpload.Path = "C:\Uploads"

'--- Set the default save location for the first file
CType(fileUpload.Form("File1"), SaFile).Path = _
"C:\Uploads\MyFirstFile\"

'--- Save first uploaded file
CType(fileUpload.Form("File1"), SaFile).Save()

Cache the upload to the web server and save the first uploaded file to a network shared drive:

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location to web server path
fileUpload.Path = "C:\Temp"

'--- Set the default save location for the first file
fileUpload.Form("File1").Path = "\\FileServer\Uploads"

'--- Save first uploaded file
fileUpload.Form("File1").Save
%>
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- (Cache location is set to C:\Temp using FileUpTempDir registry
//--- key)

//--- Set the default save location for the first file
((SaFile)fileUpload.Form["File1"]).Path =
@"\\FileServer\Uploads";

//--- Save first uploaded file
((SaFile)fileUpload.Form["File1"]).Save;
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context);

'--- (Cache location is set to C:\Temp using FileUpTempDir registry
'--- key)

'--- Set the default save location for the first file
CType(fileUpload.Form("File1"), SaFile).Path = _
"\\FileServer\Uploads"

'--- Save first uploaded file
CType(fileUpload.Form("File1"), SaFile).Save


PreserveMacBinary

PreserveMacBinary Property

Object: SoftArtisans.SAFile
Syntax: PreserveMacBinary
Type: Boolean
Read/Write: Read Only
Description:

In order to preserve both the data and resource forks of files uploaded from a Mac, you must set PreserveMacBinary on the FileUp object. (see FileUp.PreserveMacBinary) Additionally, this must be done before referencing any form elements. The PreserveMacBinary property available to the SAFile object is Read Only.

Note: When using the HttpModule with an ASP.NET upload, since the HttpModule is used for caching, this property will have no effect.
Examples:
ASP <%
If (fileUpload.Form("File1").PreserveMacBinary = True) Then
Response.Write("The first uploaded file is set to have both " & _
"the data and resource forks preserved.")
ElseIf (fileUpload.Form("File1").PreserveMacBinary = False) Then
Response.Write("The first uploaded file is NOT set to have " & _
"both the data and resource forks preserved.")
End If
%>
ASP.NET N/A


ServerName

ServerName Property

Object: SoftArtisans.SAFile
Syntax: ServerName
Type: String
Read/Write: Read Only
Description:

This property displays the complete path and name of the uploaded file on the web server's file system.

Before a Save, SaveAs, or SaveAsBlob is executed, the ServerName property contains the location of the temporary cache file used when processing uploads. After a Save, SaveAs, or SaveAsBlob, ServerName displays the complete path and name of the final location of the file.

The cache filename is always guaranteed to be unique. You can use the .ServerName property to generate a unique name when saving the file. The cache file's name is of the form saNNNN.tmp, where NNNN is a unique number. See Example 2, below.

If you intend to only upload one file, your code may be made more brief using the ServerName property of the FileUp object. Please see: SAFileUp.ServerName
Examples:

Use the ServerName property to report back the name and path of the file as it was finally saved on the server. In this example, the resulting ServerName will be 'C:\Temp\upload.tst'.

ASP <%
'--- Instantiate FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'--- Set cache/default save location
fileUpload.Path = "C:\Temp"
filename = "upload.tst"
Response.Write("The uploaded file is now cached in: " & _
fileUpload.Form("File1").ServerName & "<br />")

Response.Write("Saving the file to: " & filename & "<br />")

On Error Resume Next

'--- Save upload
fileUpload.SaveAs filename

If Err = 0 Then
Response.Write("Upload saved successfully to: " &
fileUpload.Form("File1").ServerName)
Else
'--- Handle errors
End If
%>

ServerName will display "C:\Temp\upload.tst"
C# //--- Instantiate FileUp
FileUp fileUpload = new FileUp(Context);

//--- Set cache/default save location
fileUpload.Path = @"C:\Temp";
filename = "upload.tst";

results.Append("The uploaded file is now cached in: " +
fileUpload.Form["File1"].ServerName + "<br />");

results.Append("Saving the file to: " + filename + "<br />");

//--- Save upload
fileUpload.SaveAs(filename);

results.Append("Upload saved successfully to: " +
((SaFile)fileUpload.Form["File1"]).ServerName);

ServerName will display "C:\Temp\upload.tst"
VB.NET '--- Instantiate FileUp
Dim fileUpload As New FileUp(Context)

'--- Set cache/default save location
fileUpload.Path = "C:\Temp"
filename = "upload.tst"

results.Append("The uploaded file is now cached in: " + _
fileUpload.Form("File1").ServerName + "<br />")

results.Append("Saving the file to: " + filename + "<br />")

'--- Save upload
fileUpload.SaveAs(filename)

results.Append("Upload saved successfully to: " + _
CType(fileUpload.Form("File1"), SaFile).ServerName)

ServerName will display "C:\Temp\upload.tst"


ShortFilename

ShortFilename Property

Object: SoftArtisans.SAFile
Syntax: ShortFilename
Type: String
Read/Write: Read Only
Description:

This property returns the user's original name for the uploaded file, not including any path information.

For example, if a user uploads a file from the following path on their hard drive: "C:\MyFiles\filename.txt", the ShortFilename property will return "filename.txt".

This property can be used in conjunction with the SaveAs or SaveInVirtualmethods to save a file with the user's original user's filename in a directory otherthan the one used to temporarily cache the uploaded files (stored in the Path property ). The Save method, on the other hand, will automatically save a file with the user's original filename to the directory assigned to the path property. Using SaveAs or SaveInVirtual in conjunction with ShortFilename is especially useful when you wish to dynamically set the destination of the upload based on data passed from the upload form.

If you intend to upload only one file, see also the ShortFilename property of the main FileUp object.

Examples:

Output first filename to user:

ASP | The first file you uploaded was: <%=fileUpload.Form("File1").ShortFilename%>.
C# | results.Append("The first file you uploaded was: " & ((SaFile)fileUpload.Form["File1"]).ShortFilename);
VB.NET | results.Append("The first file you uploaded was: " + CType(fileUpload.Form("File1"), SaFile).ShortFilename)

Save first file using original filename to directory chosen by the user:

ASP <%
'--- Create an instance of SoftArtisans FileUp
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")

'---Set the default path to store uploaded files
fileUpload.Path = "C:\Temp"

'--- Retrieve the user's chosen directory from the form
Dim newPath
newPath = fileUpload.Form("Directory")

'--- Save the file with the user's original filename
'--- to the user's chosen directory
fileUpload.Form("File1").SaveAs newPath & "\" & _
fileUpload.Form("File1").ShortFilename
%>
C# //--- Create an instance of SoftArtisans FileUp
FileUp fileUpload As New FileUp(Context);

//---Set the default path to store uploaded files
fileUpload.Path = @"C:\Temp";

//--- Retrieve the user's chosen directory from the form
string newPath = fileUpload.Form("Directory");

//--- Save the file with the user's original filename
//--- to the user's chosen directory
fileUpload.Form["File1"].SaveAs(newPath + "\\" +
((SaFile)fileUpload.Form["File1"]).ShortFilename);
VB.NET '--- Create an instance of SoftArtisans FileUp
Dim fileUpload As New FileUp(Context)

'---Set the default path to store uploaded files
fileUpload.Path = "C:\Temp"

'--- Retrieve the user's chosen directory from the form
Dim newPath As String = fileUpload.Form("Directory")

'--- Save the file with the user's original filename
'--- to the user's chosen directory
fileUpload.Form("File1").SaveAs(newPath + "\" + _
CType(fileUpload.Form("File1"), SaFile).ShortFilename)


TotalBytes

TotalBytes Property

Object: SoftArtisans.SAFile
Syntax: TotalBytes
Type: ASP: Long Integer; .NET: System.UInt64
Read/Write: Read Only
Description:

This property displays the actual numbers of bytes written to disk.

The value of TotalBytes is always less than or equal to the MaxBytes property .

See also the TotalBytes property for the SAFileUp object.

Examples:
ASP <%=fileUpload.Form("File1").TotalBytes%> total bytes were written to disk for the first uploaded file.
C# SaFile file1 = (SaFile)fileUpload.Form["File1"];
ulong num = file1.TotalBytes;
results.Append(num + " total bytes were written to disk for the " +
"first uploaded file.");
VB.NET Dim file As SaFile = CType(fileUpload.Form("File1"), SaFile)
Dim num As UInt64 = file.TotalBytes
results.Append(num + " total bytes were written to disk for the " + _
"first uploaded file.")


UploadContents

UploadContents Property

Object: SoftArtisans.SAFile
Syntax: UploadContents([type])
Type: Variant
Read/Write: Read Only
Description:

This property is used in conjunction with the FileUp object UseMemory property . It returns the contents of the uploaded file in one of three possible formats, depending on the value of an optional parameter, type.

The following table lists the possible values for the type parameter and the corresponding return value. Note that the default value is 0.

Value of type | Returns | Automation Definition
0 | String | BSTR
1 | An array of variants | SAFEARRAY of VARIANTS
2 | An array of binary characters | VT_UI1 | VT_ARRAY


UserFilename

UserFilename Property

Object: SoftArtisans.SAFile
Syntax: UserFilename
Type: String
Read/Write: Read Only
Description:

This property contains the name of the uploaded file on the user's hard disk, including path.

To extract just the file name, without the path, use the SAFile object's ShortFileName property instead.

The complete name of the file is dependent upon the user's operating system. If the user uploads from a Windows PC, the path will be the usual driveletter:\dir1\dir2\file.ext. UNIX users will send files in driveletter:\dir1\\file.ext format. Several customers have reported that certain browsers on Macintoshes do not report valid pathnames. We have been unable to verify this.

If you intend to only ever upload one file, you can reduce the amount of code you need to maintain by setting this property on the FileUp object, which will apply the property to the first file in the upload request. See [FileUp].UserFilename.

Examples:
ASP The first file you uploaded was:
<%=fileUpload.form("File1").UserFilename%>
C# results.Append("The first file you uploaded was: " +
((SaFile)fileUpload.Form["File1"]).UserFilename);
VB.NET results.Append("The first file you uploaded was: " + _
CType(fileUpload.Form("File1"), SaFile).UserFilename)


Form Collection

The Form collection is the container for all form elements in an upload. It is similar to the Request.Form dictionary.

There is no need for the programmer to create an instance of this object. It is created automatically when needed by the FileUp object.

Form Properties


Form Collection Properties

Count Property

Item Property


Count

Count Property

Object: SoftArtisans.UploadDictionary
Syntax: Count
Type: Long Integer
Read/Write: Read Only
Description:

This property displays the number of items in the dictionary.
Examples:
ASP <%
Response.Write ("The number of items in the form is: " & _
fileUpload.Form.Count)
%>
C# results.Append("The number of items in the forum is: " +
fileUpload.Form.Count);
VB.NET results.Append("The number of items in the forum is: " + _
fileUpload.Form.Count)


Item

Item Property

Object: SoftArtisans.UploadDictionary
Syntax: Item
Type: String or SA-File object
Read/Write: Read/Write
Description:

This property represents the value of a particular item in the dictionary.

This is the default property of the UploadDictionary object and is used to maintain compatibility with the Request object.

fileUpload.FormEx.Item("key") is equivalent to fileUpload.FormEx("key"). It is the Item property that allows this to occur.

Examples:

Loop through the form elements using the item indexer:

ASP <%
For Each x in fileUpload.FormEx
Response.Write("<tr><td align=""right"">" & _
x & "</td><td>'" & fileUpload.FormEx(x) & "'</td></tr>")
Next
%>
C# foreach (object x in fileUpload.FormEx)
{
results.Append("<tr><td align=\"right\">" +
x + "</td><td>'" + fileUpload.FormEx[x] + "'</td></tr>");
}
VB.NET For Each (x As object In fileUpload.FormEx)

results.Append("<tr><td align=""right"">" + _
x + "</td><td>'" + fileUpload.FormEx(x) + "'</td></tr>")

Next

Get the user filename of the first file uploaded in the form:

ASP | <% Dim fname = fileUpload.FormEx("File1").UserFilename %gt;
C# | string fname = ((SaFile)fileUpload.FormEx["File1"]).UserFilename;
VB.NET Dim fname As String = _
CType(fileUpload.FormEx("File1"), CType).UserFilename


FileUpProgress Object

The SoftArtisans.FileUpProgress object contains various methods and properties that let you monitor the progress of the upload.

It also contains the Items object that returns a collection of Progress Items.

Instantiating the Progress Object:

ASP Set prg = Server.CreateObject("SoftArtisans.FileUpProgress")
C# FileUpProgress progress = null;

try
{
//--- Instantiate the FileUpProgress object
progress = new FileUpProgress();
...
}
catch
{
...
}
finally
{
//--- Always call Dispose in the finally block
if (progress != null)
{
progress.Dispose();
progress = null;
}
}
VB.NET Dim progress As FileUpProgress

Try
'--- Instantiate the FileUpProgress object
progress = New FileUpProgress()
...
Catch
...
Finally
'--- Always call Dispose in the finally block
If Not (progress Is Nothing) Then
progress.Dispose()
progress = Nothing
End If
End Try

After that, all methods and properties are available to you.

Methods

Properties


FileUpProgress Methods

This section contains the methods implemented by the FileUpProgress object.

NextProgressID Method


NextProgressID

NextProgressID Property

Object: SoftArtisans.FileUpProgress
Syntax: NextProgressID
Description:

This method returns the next unused ProgressID. See the ProgressID property for more information.

Examples:

Loop through the form elements using the item indexer:

ASP <%
fileUpload.ProgressID = fileUpload.NextProgressID
%>
C# | fileUpload.ProgressID = fileUpload.NextProgressID();
VB.NET | fileUpload.ProgressID = fileUpload.NextProgressID()

Because progress indication requires the coordination of several scripts, please see the appropriate Programmer's Guide for a complete sample the demonstrates the use of the FileUp ProgressID property.

  • Programmer's Guide for ASP: Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator


Progress Object Properties

This section contains the properties implemented by the Progress object.

Items Property

Percentage Property

ProgressID Property

TotalBytes Property

TransferComplete Property

TransferredBytes Property


Items Collection

The Items Collection object is the container for all of the Progress Items currently executing. Progress Items for any transfers not yet started or already completed will not be part of the collection.

Note: This collection is not available in ASP.NET.

The Items Collection contains the following properties:

Count

Item


Count

Count Property

Object: SoftArtisans.FileUpProgress Items Collection
Syntax: Count
Type: Long
Read/Write: Read Only
Description:

Returns the number of FileUpProgress Items in the collection.

Note: This property is not available in ASP.NET.
Examples:
ASP | <% Response.Write("There are currently " & progress.Items.Count & " progress items.") %>
ASP.NET | N/A


FileUpProgress Items Collection

Object: FileUpProgress Items Collection
Syntax: Item
Type: ProgressItem
Read/Write: Read Only
Description:

Returns a single ProgressItem object in a FileUpProgress Items collection.

Note: This collection is not available in ASP.NET.

The ProgressItem object has four properties:

Percentage

ProgressID

TotalBytes

TransferredBytes

Examples:
ASP | <% Set inProgressUpload = progress.Items(1) %>
ASP.NET | N/A


Percentage

Percentage Property

Object: SoftArtisans.FileUpProgress Item
Syntax: Percentage
Type: Decimal
Read/Write: Read Only
Description:

This property returns what percentage of the transfer is complete. This is determined by the following formula:

TransferredBytes = ---------------- * 100 Total
Note: This property is not available in ASP.NET.
Examples:
ASP <% Set inProgressUpload = progress.Items(1)
Response.Write("Percentage complete of upload: " & _
inProgressUpload.Percentage) %>
ASP.NET N/A


ProgressID

ProgressID Property

Object: SoftArtisans.FileUpProgress Item
Syntax: ProgressID
Type: Integer
Read/Write: Read/Write
Description:

This property sets or gets the ID of the current upload. This lets you track the progress of the current upload.

To view the progress of a specific upload, you must assign a ProgressID to it. Then create a SoftArtisans.FileUpProgress object and use the same ProgressID. The FileUpProgress object has properties that update in real-time to reflect the current and total bytes to be uploaded.

To get the next unused ProgressID, use the NextProgressID method .

The ID must be between 1 and 500. The ID is guaranteed to be unique at any one time, but it is not guaranteed to be unique for the duration of IIS's execution.

SoftArtisans assumes that Web servers will not use more than 500 simultaneous uploads. Since ASP has a fixed maximum number of concurrent pages that can be executed (25 in Windows 2000, 10 in IIS 4), even an 8-processor machine would handle a maximum of 200 uploads if all processors were totally dedicated to uploads. The maximum of 500 is easily changed, so if you have higher volume than this, please contact us .

Note: This property is not available in ASP.NET.
Examples:
ASP <% Set inProgressUpload = progress.Items(1)
Response.Write("Progress ID of upload: " & _
inProgressUpload.ProgressID) %>
ASP.NET N/A


TotalBytes

TotalBytes Property

Object: SoftArtisans.FileUpProgress Item
Syntax: TotalBytes
Type: Integer
Read/Write: Read Only
Description:

This property returns the total number of bytes to be transferred for this ProgressID.

Note: This property is not available in ASP.NET.
Examples:
ASP <% Set inProgressUpload = progress.Items(1)
Response.Write("Total Bytes of upload: " & _
inProgressUpload.TotalBytes) %>
ASP.NET N/A


TransferredBytes

TransferredBytes Property

Object: SoftArtisans.FileUpProgress Item
Syntax: TransferredBytes
Type: Integer
Read/Write: Read Only
Description:

This property returns the number of bytes that have been received by the server.

Note: This property is not available in ASP.NET.
Examples:
ASP <% Set inProgressUpload = progress.Items(1)
Response.Write("Transferred Bytes of upload: " & _
inProgressUpload.TransferredBytes) %>
ASP.NET N/A


Percentage

Percentage Property

Object: SoftArtisans.FileUpProgress
Syntax: Percentage
Type: Decimal
Read/Write: Read Only
Description:

This property returns what percentage of the transfer is complete. This is determined by the following formula:

TransferredBytes = ---------------- * 100 Total
Examples:
ASP <%
intPercentComplete = progress.Percentage
%>
C# | string strPercent = progress.Percentage.ToString("N") + "%";
VB.NET | Dim strPercent As String = progress.Percentage.ToString("N") + "%"

Because progress indication requires the coordination of several scripts, please see the appropriate Programmer's Guide for a complete sample the demonstrates the use of the FileUp ProgressID property.

  • Programmer's Guide for ASP Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator


ProgressID

ProgressID Property

Object: SoftArtisans.FileUpProgress
Syntax: ProgressID
Type: Integer
Read/Write: Read/Write
Description:

This property sets or gets the ID of the current upload. This lets you track the progress of the current upload.

To view the progress of a specific upload, you must assign a ProgressID to it. Then create a SoftArtisans.FileUpProgress object and use the same ProgressID. The FileUpProgress object has properties that update in real-time to reflect the current and total bytes to be uploaded.

Pass the ProgressID from page to page in the query string or in a cookie. You cannot pass the ProgressID as a form value. The example in Adding a Server-Side Progress Indicator demonstrates passing the ProgressID in the query string.

To get the next unused ProgressID, use the NextProgressID method .

The ID must be between 1 and 500. The ID is guaranteed to be unique at any one time, but it is not guaranteed to be unique for the duration of IIS's execution.

SoftArtisans assumes that Web servers will not use more than 500 simultaneous uploads. Since ASP has a fixed maximum number of concurrent pages that can be executed (25 in Windows 2000, 10 in IIS 4), even an 8-processor machine would handle a maximum of 200 uploads if all processors were totally dedicated to uploads. The maximum of 500 is easily changed, so if you have higher volume than this, please contact us .

Examples:
ASP <%
fileUpload.ProgressID = CInt(Request.QueryString("progressid"))
%>
C# fileUpload.ProgressID = (int)Request.QueryString["progressid"];
VB.NET fileUpload.ProgressID = _
CType(Request.QueryString("progressid"), Integer)

Because progress indication requires the coordination of several scripts, please see the appropriate Programmer's Guide for a complete sample the demonstrates the use of the FileUp ProgressID property.

  • Programmer's Guide for ASP Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator


TotalBytes

TotalBytes Property

Object: SoftArtisans.FileUpProgress
Syntax: TotalBytes
Type: Integer
Read/Write: Read Only
Description:

This property returns the total number of bytes to be transferred for this ProgressID.
Examples:
ASP <%
intTotalBytes = progress.TotalBytes
%>
C# | cellTotalBytes.Text = progress.TotalBytes.ToString();
VB.NET | cellTotalBytes.Text = progress.TotalBytes.ToString()

Because progress indication requires the coordination of several scripts, please see the appropriate Programmer's Guide for a complete sample the demonstrates the use of the FileUp ProgressID property.

  • Programmer's Guide for ASP Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator


TransferComplete

TransferComplete Property

Object: SoftArtisans.FileUpProgress
Syntax: TransferComplete
Type: Boolean
Read/Write: Read Only
Description:

This property returns True when the transfer of the current ProgressID is complete.
Examples:
ASP <%
If (Progress.TransferComplete = True) Then
Response.Write("File uploaded successfully!")
End If
%>
C# if (Progress.TransferComplete = true)
{
results.Append("File uploaded successfully!");
}
VB.NET If (Progress.TransferComplete = True) Then
results.Append("File uploaded successfully!")
End If

Because progress indication requires the coordination of several scripts, please see the appropriate Programmer's Guide for a complete sample the demonstrates the use of the FileUp ProgressID property.

  • Programmer's Guide for ASP Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator

Example

Because progress indication requires the coordination of several scripts, please see the appropriate Programmer's Guide for a complete sample the demonstrates the use of the FileUp ProgressID property.

  • Programmer's Guide for ASP Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator


TransferredBytes

TransferredBytes Property

Object: SoftArtisans.FileUpProgress
Syntax: TransferredBytes
Type: Integer
Read/Write: Read Only
Description:

This property returns the number of bytes that have been received by the server.
Examples:
ASP <%
intBytesTransferred = progress.TransferredBytes
%>
C# | cellTransferredBytes.Text = progress.TransferredBytes.ToString();
VB.NET | cellTransferredBytes.Text = progress.TransferredBytes.ToString()

Because progress indication requires the coordination of several scripts, please see the appropriate Programmer's Guide for a complete sample the demonstrates the use of the FileUp ProgressID property.

  • Programmer's Guide for ASP Adding a Server-Side Progress Indicator
  • Programmer's Guide for ASP.NET: Adding a Server-Side Progress Indicator


The Archive Object

The Archive object is SoftArtisans Archive's principal object. When you create an instance of the Archive object, Archive automatically creates instances of the sub-objects ArchiveItemCollection and ArchiveItem.

To create a server-side instance of the Archive object, use ASP's Server.CreateObject, as follows.

Set objArchive = Server.CreateObject("Softartisans.Archive")

To create a client-side instance of the Archive object, use HTML's <object>tag, as follows.

<Object Classid="clsid:D3400FEE-041F-11D3-B1C5-00A0C9B4587A" Codebase="localhost/SAXFileSamples/saxfile.cab"
      ID="arch"></Object>

Classid specifies Archive's unique class id, clsid:D3400FEE-041F-11D3-B1C5-00A0C9B4587A. Codebase specifies the location of saxfile.cab, which contains SAArch.dll (Archive's dll). Id assigns a name to the created instance of SoftArtisans Archive.

Methods

Properties


Archive Methods

This section contains the methods implemented by the Archive object.

AddFile Method
CloseArchive Method
CreateArchive Method
Extract Method
OpenArchive Method
RemoveFile Method


AddFile

AddFile Method

Object: Archive
Syntax: AddFile ([in] Filename, [in] bRecursive)
Description: This method adds files to the archive. Filename can contain the name of a file or a directory. Call OpenArchive or CreateArchive before using the AddFile Method.

If you set the optional bRecursive to True, any directories or folders are recursively added to the archive. The default value of bRecursive is False. To preserve a file's complete path in an archive, set bRecursive to True and set the PreservePath property to True. Note: to preserve paths when creating a Zip file, set ArchiveType to 3.
Example:
Set Arch = CreateObject("SoftArtisans.Archive") ArchiveName = "c:\temp\Arch.cab"
            '--- Set ArchiveType to Cabinet format Arch.ArchiveType = 2 '--- Save Path Information
            Arch.PreservePath = True '--- Create the Cabinet file Arch.CreateArchive ArchiveName
            '--- Add files to the cabinet file1 = "c:\folder\file1.txt" file2 = "c:\folder\file2.txt"
            file3 = "c:\folder\file3.txt" '--- Add the files to the archive. '--- To include
            a complete path '--- in the archive, set the second '--- parameter of AddFile to
            True. Arch.AddFile file1, True Arch.AddFile file2, True Arch.AddFile file3, True
            Arch.CloseArchive


CloseArchive

CloseArchive Method

Object: | Archive
Syntax: | CloseArchive
Description: | This method closes a currently opened archive. In most cases, you must use this method in order to s ave any additions or deletions to the archive. If you do not clsoe the archive, all changes will be lost


CreateArchive

CreateArchive Method

Object: | Archive
Syntax: | CreateArchive ([in] Filename)
Description: | This method creates a new archive with the name specified in Filename. Filename must be a valid filename. It can include a complete path.


Extract

Extract Method

Object: | Archive
Syntax: | Extract ([in] Filename)
Description: | This method extracts files from an archive. If no Filename is specified, this method extracts the entire contents of the archive.

Example:

<% Set Arch = Server.CreateObject("Softartisans.Archive") ... '--- '--- Set the
        path to which you want to extract files. Arch.ExtractPath = "C:\Temp\Extract" '---
        '--- Extract Files Arch.Extract() ... %>


OpenArchive

OpenArchive Method

Object: | Archive
Syntax: | OpenArchive ([in] filename)
Description: | This method opens an existing archive.


RemoveFile

RemoveFile Method

Object: | Archive
Syntax: | RemoveFile ([in] Filename)
Description: | This method removes the specified file from an archive.


SoftArtisans Archive Properties

This section contains the properties implemented by the Archive object.

ArchiveName Property
ArchiveType Property
EnableSigning Property
Entries Property
Exists Property
ExpirationDate Property
ExtractPath Property
Password Property
PreservePath Property
SelfExtractFile Property
SelfExtractHeaderFile Property
SignCode Property
TempPath Property
Version Property


ArchiveName

ArchiveName Property

Object: | Archive
Syntax: | ArchiveName
Type: | String
Read/Write: | Read Only
Description: | This property returns the name of the archive you're opening or creating.


ArchiveType

ArchiveType Property

Object: Archive
Syntax: ArchiveType
Type: Integer
Read/Write: Read/Write
Description:

This property indicates whether the Archive to open or create is in Zip or Microsoft Cabinet format (cab). Set ArchiveType before using the CreateArchive or OpenArchivemethods.

ArchiveType Values
1 | Zip If ArchiveType is set to 1, Archive can preserve directory structure when extracting a Zip file, but not when creating a Zip file.
2 | Cab If ArchiveType is set to 2, Archive can preserve directory structure both when extracting and when creating a Cab file.
3 | Zip If ArchiveType is set to 3, Archive can preserve directory structure both when extracting and when creating a Zip file.

To preserve paths when creating or extracting an archive file, set PreservePath to True.

Example:
Set Arch = CreateObject("SoftArtisans.Archive") ArchiveName = "c:\temp\Arch.cab"
            '--- Set ArchiveType to 3 to create a Zip '--- file, and to allow Archive to store
            paths '--- in the Zip. Arch.ArchiveType = 3 '--- Save Path Information Arch.PreservePath
            = True '--- Create the Cabinet file Arch.CreateArchive ArchiveName '--- Add files
            to the cabinet file1 = "c:\folder\file1.txt" file2 = "c:\folder\file2.txt" file3
            = "c:\folder\file3.txt" '--- Add the files to the archive. '--- To include a complete
            path '--- in the archive, set the second '--- parameter of AddFile to True. Arch.AddFile
            file1, True Arch.AddFile file2, True Arch.AddFile file3, True Arch.CloseArchive


EnableSigning

EnableSigning Property

Object: | Archive
Syntax: | EnableSigning
Type: | Boolean
Read/Write: | Read/Write
Description: | Use this property to indicate whether the Cab is going to be signed. If set to True, the Cab is going to be signed. The default value is False.

Example 1:

<%@ Language=VBScript%> <HTML> ... The EnableSigning property is set
        to: <%=Arch.EnableSigning%>. ... </HTML>

Example 2:

<% Set Arch = Server.CreateObject("Softartisans.Archive") ... '--- '--- Turn
        the EnableSigning Property On '--- Arch.EnableSigning = True ... %>


Entries

Entries Property

Object: | Archive
Syntax: | Entries
Type: | ArchiveItemCollection
Read/Write: | Read Only
Description: | This property returns the collection of archived items to be added to the archive when it's created or retrieved from the archive after it's opened. If you are opening an archive, this property returns a list of all files in the archive. For each ZIP format file, you can use the CompressedSize and UncompressedSize properties. For Microsoft Cabinet format files you can use only the UncompressedSize property. See also the Name and Path properties.


Exists

Exists Property

Object: | Archive
Syntax: | Exists (Filename)
Type: | Boolean
Description: | This property returns True or False, indicating whether a file exists within the current archive. The specified Filename must be complete, with name and relative path of the file inside the archive.


ExpirationDate

ExpirationDate Property

Object: | Archive
Syntax: | ExpirationDate
Type: | Date
Read/Write: | Read Only
Description: | This property returns the expiration date of the current evaluation version. A full, non-evaluation version returns an empty expiration date.

Example:

<%@ Language=VBScript%> <HTML> ... This evaluation version of SoftArtisans
        Archive expires on <%=Arch.ExpirationDate%>. ... </HTML>


ExtractPath

ExtractPath Property

Object: | Archive
Syntax: | ExtractPath
Type: | String
Read/Write: | Read/Write
Description: | This property returns the complete path for the destination of the extracted archive. You can also use this property to set the path of the extracted archive -- the archive's content will be extracted to the specified directory. See the Extract method for more information.

Example 1:

<%@ Language=VBScript%> <HTML> ... The directory to which SoftArtisans
        Archive will extract files is: <%=Arch.ExtractPath%>. ... </HTML>

Example 2:

<% Set Arch = Server.CreateObject("Softartisans.Archive") ... '--- '--- Set the
        path to which you want to extract files. Arch.ExtractPath = "C:\Temp\Extract" '---
        '--- Extract Files Arch.Extract() ... %>


Password

Password Property

Object: | Archive
Syntax: | Password
Type: | String
Read/Write: | Write Only
Description: | This property works for ZIP format only.

Example:

<% Set Arch = Server.CreateObject("Softartisans.Archive") ... '--- '--- Set the
        password for the ZIP file. Arch.Password = "Password" ... %>


PreservePath

PreservePath Property

Object: Archive
Syntax: PreservePath
Type: Boolean
Read/Write: Read/Write
Description: When PreservePath is set to True, Archive will preserve file paths when extracting or creating an archive file.

When creating an archive, to preserve a file's complete path in an archive, set PreservePath to True and set the second parameter of the AddFile method to True. If you are creating a zip file, set ArchiveType to 3.
Example:
Set Arch = CreateObject("SoftArtisans.Archive") ArchiveName = "c:\temp\Arch.cab"
            '--- Set ArchiveType to Cabinet format Arch.ArchiveType = 2 '--- Save Path Information
            Arch.PreservePath = True '--- Create the Cabinet file Arch.CreateArchive ArchiveName
            '--- Add files to the cabinet file1 = "c:\folder\file1.txt" file2 = "c:\folder\file2.txt"
            file3 = "c:\folder\file3.txt" '--- Add the files to the archive. '--- To include
            a complete path '--- in the archive, set the second '--- parameter of AddFile to
            True. Arch.AddFile file1, True Arch.AddFile file2, True Arch.AddFile file3, True
            Arch.CloseArchive


SelfExtractFile

SelfExtractFile Property

Object: | Archive
Syntax: | SelfExtractFile
Type: | String
Read/Write: | Write Only
Description: | When creating ZIP format archives, use this property to provide the name of a self-extractable file. A self-extractable file is created. Self-extracting files are executable files with a .EXE extension. When the user launches the file, all files in the archives are extracted. See also the SelfExtractHeaderFile property.

Example:

<% Set Arch = Server.CreateObject("Softartisans.Archive") ... '--- '--- Set the
        path and filename of the self-extracting file that is going to be created. Arch.SelfExtractFile
        = "C:\temp\Extract.exe" '--- '--- Set the path and filename of the header file that
        is required to create self-extracting files. Arch.SelfExtractHeaderFile = "C:\Program
        Files\Software Artisans\Archive\seazip.exe" ... %>


SelfExtractHeaderFile

SelfExtractHeaderFile Property

Object: | Archive
Syntax: | SelfExtractHeaderFile
Type: | String
Read/Write: | Write Only
Description: | This property works with the SelfExtractFile property. It returns the pathname of the seazip.exe file, which is distributed with SoftArtisans Archive.This header file is required to create self-extracting files.

Example:

<% Set Arch = Server.CreateObject("Softartisans.Archive") ... '--- '--- Set the
      path and filename of the self-extracting file that is going to be created. Arch.SelfExtractFile
      = "C:\temp\Extract.exe" '--- '--- Set the path and filename of the header file that
      is required to create self-extracting files. Arch.SelfExtractHeaderFile = "C:\Program
      Files\Software Artisans\Archive\seazip.exe" ... %>


SignCode

SignCode Property

Object: Archive
Syntax: SignCode
Type:
Read/Write:
Description: This property indicates the pathname of the signcode.exe file. This property is for Microsoft Cabinet format only.

In the following table, the columns contain the following information:
  • Property. The name of the property you use to set the value of the parameter listed in the third column. Note that the property should not include the switch listed in the second column.
  • Switch. The switch evoked in signcode.exe by using the property (listed in the first column).
  • Parameter. Parameter for signcode.exe.
  • Description. Description of parameter

 | Maps to SignCode Information
Property | Switch | Parameter | Description
SPCFile | -spc | <file> | SPC file containing software publishing certificates.
PFKFile | -v | <pvkfile> | PVK file containing the private key.
KeyName | -k | <KeyName> | Key container name.
SignedFileTextName | -n | <name> | Text name representing content of the file to be signed.
Info | -i | <info> | Location to find more information about content (usually a URL).
Provider | -p | <provider> | Name of the cryptographic provider on the system.
Cryptype | -y | <type> | Cryptographic provider type to use.
KeyType | -ky | <keytype> | Key type. <signature|exchange|<integer>>
Authority | -$ | <authority> | Signing authority of the certificate. <individual|commercial> Default to using certificate's highest capability.
Algorithm | -a | <algorithm> | Hashing algorithm for signing. <md5|sha1> Defaults to md5.
TimeStampURL | -t | <URL> | TimeStamp server's http address.
TimeStampTrialCount | -tr | <number> | The number of timestamp trials until succeeds. Defaults to 1.
TimeSTampTrialDelay | -tw | <number> | The number of seconds delay between each timestamp. Defaults to 0.
DllNameSignature | -j | <dllName > | Name of the dll that provides attributes of the signature.
DllSignatureParam | -jp | <param> | Parameter to be passed to the dll.
X509File | -c | <file> | X509 file containing encoded software publishing certificate.
StoreCert | -s | <store> | Cert store containing certs. Default to my store.
Location | -r | <location> | Location of the cert store in the registry. <localMachine|currentUser> Defaults to currentUser.
Policy | -sp | <policy> | Add all the certificates in the chain or add until one cert in the chain is from the spc store. <chain|spcstore> Defaults to spcstore.
CommonName | -cn -x | <name> | The common name of the certificate. Do not sign the file. Only Timestamp the file.

Note: To sign with a SPC file, the required options are -spc and -v if your private key is in a PVK file. If your private key is in a registry key container, the required options are -spc and -k.

Example:

<% Set Arch = Server.CreateObject("Softartisans.Archive") ... '--- '--- Set the
      executable path for the Signcode program. '--- Arch.SignCode = "C:\SDK-java.31\bin\packsign\signcode.exe"
      ... %>


TempPath

TempPath Property

Object: Archive
Syntax: TempPath
Type: String
Read/Write: Read/Write
Description:

This property defines the temporary directory for storing files. If this property is not set, SoftArtisans Archive will use the system's temporary path to store the temporary files that it generates.

This property should be set immediately after creating an instance of SoftArtisans Archive.

The anonymous (IUSR_machinename) or authenticated user for SoftArtisans Archive must have Read, Write and Delete priviledges for this directory.

Example 1:

<%@ Language=VBScript%> <HTML> ... The temporary directory for SoftArtisans
        Archive files is <%=Arch.TempPath%>. ... </HTML>

Example 2:

<% Set Arch = Server.CreateObject("Softartisans.Archive") '--- '--- Set the temporary
        path to store extracted files. '--- This should be set immediately after creating
        an instance. Arch.TempPath = "C:\Temp" ... %>


Version

Version Property

Object: | Archive
Syntax: | Version
Type: | String
Read/Write: | Read Only
Description: | This property returns the current version number of SoftArtisans Archive.

Example:

<%@ Language=VBScript%> <HTML> ... The version of SoftArtisans Archive
        is <%=Arch.Version%>. ... </HTML>


The ArchiveItemCollection Object

The ArchiveItemCollection object represents the collection of files in an archive. When you create an instance of the Archive object, Archive automatically creates an instance of the ArchiveItemCollection object.

ArchiveItemCollection Methods

ArchiveItemCollection Properties


ArchiveItemCollection Methods

This section contains the methods implemented by the ArchiveItemCollection object.

Add Method

Remove Method


Add

Add Method

Object: | ArchiveItemCollection
Syntax: | Add
Description: | This method adds a file to the collection of files in an archive.


Remove

Remove Method

Object: | ArchiveItemCollection
Syntax: | Remove
Description: | This method removes a file from the collection of files in an archive.


ArchiveItemCollection Properties

This section contains the properties implemented by the ArchiveItemCollection object.

Count Property

Item Property


Count

Count Property

Object: ArchiveItemCollection
Syntax: Count
Type: Long Integer
Read/Write: Read Only
Description: This property displays the total number of files in the current archive.

Use this property while opening an archive to display the total number of files in it.

When appending to an existing archive, this property will display the total number of files in the resulting archive.
Example:
Set Arch = Server.CreateObject("SoftArtisans.Archive") ArchiveName = "c:\folder1\file.zip"
            ExtractPath = "c:\folder2" Arch.ArchiveType = 1 Arch.OpenArchive ArchiveName Response.Write
            ("File.zip contains " & Arch.Entries.Count & ":") Dim item For Each item
            in Arch.Entries Response.Write "<br>" & item.name Next Arch.ExtractPath
            = ExtractPath Arch.Extract() Arch.CloseArchive Set Arch = Nothing


Item

Item Property

Object: ArchiveItemCollection
Syntax: Item
Type: Archive Item
Read/Write: Read Only
Description: This property returns an ArchiveItem object, which represents a single file in an archive.
Example:
Set Arch = Server.CreateObject("SoftArtisans.Archive") ArchiveName = "c:\folder1\file.zip"
            ExtractPath = "c:\folder2" Arch.ArchiveType = 1 Arch.OpenArchive ArchiveName Response.Write
            ("File.zip contains " & Arch.Entries.Count & ":") Dim item For Each item
            in Arch.Entries Response.Write "<br>" & item.name Next Arch.ExtractPath
            = ExtractPath Arch.Extract() Arch.CloseArchive Set Arch = Nothing


ArchiveItem Object

The ArchiveItem object represents a single file in an archive, that is, an item in an ArchiveItemCollection. When you create an instance of the Archive object, Archive automatically creates an instance of the ArchiveItem object.

ArchiveItem Methods

ArchiveItem Properties


ArchiveItem Methods

This section contains the methods implemented by the ArchiveItem object.

Extract Method

Remove Method


Extract

Extract Method

Object: | ArchiveItem
Syntax: | Extract
Description: | This method extracts an item from an archive.


Remove

Remove Method

Object: | ArchiveItem
Syntax: | Remove
Description: | This method removes an item from an archive.


ArchiveItem Properties

This section contains the properties implemented by the ArchiveItem object.

CompressedSize Property

Name Property

Path Property

UnCompressedSize Property


CompressedSize

CompressedSize Property

Object: | ArchiveItem
Syntax: | CompressedSize
Type: |
Read/Write: |
Description: | This property returns the compressed size of the file, in bytes, when you open an archive. This property is not available for Microsoft Cabinet format files.


Name

Name Property

Object: | ArchiveItem
Syntax: | Name
Type: | String
Read/Write: | Read Only
Description: | This property returns the filename for each file you are going to add to the archive you are creating.


Path

Path Property

Object: | ArchiveItem
Syntax: | Path
Type: | String
Read/Write: | Read Only
Description: | This property returns the directory path (not including the file's name) for each file you are going to add to the archive you are creating.


UncompressedSize

UncompressedSize Property

Object: | ArchiveItem
Syntax: | UncompressedSize
Type: |
Read/Write: |
Description: | This property returns the uncompressed size of the file, in bytes, when you open an archive.


The FileManager Object

To create a server-side instance of the FileManager object, use ASP's Server.CreateObject, as follows.

Set objFileManager = Server.CreateObject("SoftArtisans.FileManager")

To create a client-side instance of the FileManager object, use HTML's <object>tag, as follows.

<object classid="clsid:E7B62F4E-82F4-11D2-BD41-00105A0A7E89" codebase="localhost/SAXFileSamples/saxfile.cab"
        id="objFileManager"> </object>

Classid specifies FileManager's unique class id, clsid:E7B62F4E-82F4-11D2-BD41-00105A0A7E89. Codebase specifies the location of saxfile.cab, which contains SAFilMgr.dll (FileManager's dll). Id assigns a name to the created instance of SoftArtisans FileManager.

The FileManager object automatically creates several sub-objects:

BinaryStream, Drive, File, Folder, PermItem, and TextStream.
FileManager Reference Contents
  • FileManager Methods
  • FileManager Properties


FileManager Methods

BuildPath
CopyFile
CopyFolder
CreateBinaryFile
CreateFile
CreateFolder
CreateTextFile
CreateUniqueFile
DecryptFile
DeleteFile
DeleteFolder
DriveExists
EncryptFile
ExportToBlob
FileExists
FolderExists
GetAbsolutePathname
GetBaseName
GetDrive
GetDriveName
GetExtensionName
GetFile
GetFileName
GetFolder
GetParentFolderName
GetSpecialFolder
GetTempName
ImportFromBlob
INIDeleteKey
INIDeleteSection
INIReadBoolean
INIReadInteger
INIReadString
INIWriteBoolean
INIWriteInteger
INIWriteString
LogonUser
MoveFile
MoveFolder
OpenBinaryFile
OpenTextFile
RegisterDLL
RevertToSelf


BuildPath

BuildPath Method

Object: | FileManager
Syntax: | BuildPath ([in] Path, [in] Name)
Description: | This method appends a name to an existing path. The path argument specifies the path to which the name is appended. The path listed may be either absolute or relative.


CopyFile

CopyFile Method

Object: | FileManager
Syntax: | CopyFile ([in] Source, [in] Destination, [in, optional] OverWrite)
Description: | This method copies a file from the source to the destination location. By default, it overwrites the destination file. Set OverWrite to False to not overwrite the destination file.


CopyFolder

CopyFolder Method

Object: | FileManager
Syntax: | CopyFolder ([in] SourceDirectory, [in] DestinationDirectory, [in, optional] OverWrite)
Description: | This method copies the source folder, sub-folders, and files to another location. If OverWrite is True, all similarly named files are overwritten. It is True by default. Set OverWrite to False to not overwrite the destination files.


CreateBinaryFile

CreateBinaryFile Method

Object: | FileManager
Syntax: | CreateBinaryFile ([in] Name, [in] OverWrite)
Returns: | A BinaryStream object
Description: | This method creates a new file and returns a BinaryStream object so you can read and write the contents of the file. You must specify the complete path of the file. If you want to create a file in the current directory, use the CreateBinaryFile method of the Folder object. If OverWrite is True, and the file already exists, it will be overwritten. It is True by default.


CreateFile

CreateFile Method

Object: | FileManager
Syntax: | CreateFile ([in] Filename, [in, optional] OverWrite)
Description: | This method creates the specified file. By default, it will overwrite the destination file. Set OverWrite to False to not overwrite the destination file.


CreateFolder

CreateFolder Method

Object: | FileManager
Syntax: | CreateFolder ([in] FolderName)
Returns: | A Folder object
Description: | This method creates the specified folder. You must specify the complete path of the folder.


CreateTextFile

CreateTextFile Method

Object: | FileManager
Syntax: | CreateTextFile ([in] Name, [in] OverWrite, [in] Unicode)
Returns: | A TextStream object
Description: | This method creates a new file in the current folder and returns a TextStream object so you can read and write the contents of the file. You must specify the complete path of the file. If you want to create a file in the current directory, use the Folder object. If OverWrite is True, and the file already exists, it will be overwritten. It is True by default. If Unicode is True, the file will be created in Unicode format. It is False by default.


CreateUniqueFile

CreateUniqueFile Method

Object: | FileManager
Syntax: | CreateUniqueFile ([in] Directory, [in] Prefix)
Returns: | A string containing the name of the newly created file
Description: | This method creates a uniquely named file in the specified directory, with the specified Prefix. For example, if the directory is c:\temp and the Prefix is ab, this method creates a file named c:\temp\abNNN.tmp where NNN is unique and different from any other file in the same directory.


DecryptFile

DecryptFile Method

Object: FileManager
Syntax: objFileManager.DecryptFile ([in] InFilename, [in] OutFileName, [in] Password, [in, optional, defaultvalue(1)] saEncType)
Description: This method decrypts the file specified by InFileNameand saves the result to the OutFileNamelocation. If the password is incorrect, the file will be saved as OutFileNamebut the decryption will fail.

FileManager allows you to select either TwoFish or RSAencryption. TwoFish encryption is 128-bit. RSA encryption is either 40-bit or 128-bit, depending on the system. To determine whether the system supports 128-bit encryption, check Internet Explorer's "About" (in IE's Help menu).

DecryptFile Parameters
InFileName | The encrypted file
OutFileName | FileManager will save the decrypted file to this location
Password | The password set by Encrypt or EncryptFile. If the password is incorrect, the file will be saved as OutFileNamebut the decryption will fail.
saEncType The encryption type, which may be either TwoFish encryption, or CryptoAPI. Assign saEncTypeby name or number:

1 | SARSA
2 | SATWOFISH
3 | SARSAHIGH
4 | SARSALOW


DeleteFile

DeleteFile Method

Object: | FileManager
Syntax: | DeleteFile ([in] Filename, [in, optional] Force)
Description: | This method deletes a file from the web server's hard disk. The filename must contain the entire valid path. If Force is True, the file is deleted, even if it is marked as read-only. By default, Force is False.


DeleteFolder

DeleteFolder Method

Object: | FileManager
Syntax: | DeleteFolder ([in] FolderName, [in] Force)
Description: | This method deletes the specified folder, sub-folders, and files. If Force is True, read-only files will be deleted as well. By default, Force is False.


DriveExists

DriveExists Method

Object: | FileManager
Syntax: | DriveExists ([in] Drivename)
Returns: | True or False
Description: | This method determines whether a specified Drive exists.


EncryptFile

EncryptFile Method

Object: FileManager
Syntax: objFileManager.EncryptFile ([in] InFilename, [in] OutFilename, [in] Password, [in, optional, defaultvalue(1)] saEncType)
Description:

This method encrypts the file specified by InFileNameand saves the result to the OutFileNamelocation.

FileManager allows you to select either TwoFish or RSAencryption. TwoFish encryption is 128-bit. RSA encryption is either 40-bit or 128-bit, depending on the system. To determine whether the system supports 128-bit encryption, check Internet Explorer's "About" (in IE's Help menu).

EncryptFile Parameters
InFileName | The file to encrypt
OutFileName | FileManager will save the encrypted file to this location.
Password Use this password to decrypt the file with either DecryptFile or Decrypt.

Important! Remember the password. You will not be able to recover the file without it.
saEncType The encryption type, which may be either RSA encryption or TwoFish encryption. Assign saEncTypeby name or number:

1 | SARSA
2 | SATWOFISH
3 | SARSAHIGH
4 | SARSALOW


ExportToBlob

ExportToBlob Method

Object: | FileManager
Syntax: | ExportToBlob ([in] Source, [in] recordset("column-name"))
Description: | This method writes a Binary Large OBject (BLOB) into a database from a source file in the specified location. The object is saved into the field specified in the column-name argument. The recordset argument must specify a valid ADO recordset.


FileExists

FileExists Method

Object: | FileManager
Syntax: | FileExists ([in] Filename)
Returns: | True or False
Description: | This method determines if a specified file exists. It is useful to check if a file exists before attempting to execute the GetFile method.


FolderExists

FolderExists Method

Object: | FileManager
Syntax: | FolderExists ([in] DirectoryName)
Returns: | True or False
Description: | This method determines if a specified directory exists. It is useful to check if a folder exists before attempting to execute the GetFolder method .


GetAbsolutePathname

GetAbsolutePathname Method

Object: | FileManager
Syntax: | GetAbsolutePathname ([in] Pathspec)
Returns: | A string containing a complete and unambiguous path derived from the PathSpecargument
Description: | This method returns a string containing a complete and unambiguous path that is derived from the PathSpec argument. The path is considered complete and unambiguous if it contains a complete reference from the root of the drive.


GetBaseName

GetBaseName Method

Object: | FileManager
Syntax: | GetBaseName ([in] Pathspec)
Returns: | A string containing the base name of a file or folder, minus any file extension, from a specified path specification
Description: | This method returns a string containing the base name of a file or folder, which is derived from the PathSpec argument.


GetDrive

GetDrive Method

Object: | FileManager
Syntax: | GetDrive ([in] DriveSpec)
Returns: | A drive object corresponding to the drive in the DriveSpec argument
Description: | This method returns a drive object corresponding to the drive in the DriveSpec argument. The DriveSpec argument can be a drive letter (c), a drive letter with a colon appended (c:), a drive letter with a colon and path separator appended (c:\), or any network share specification (\\computer2\share1).


GetDriveName Method

Object: | FileManager
Syntax: | GetDriveName ([in] DriveSpec)
Returns: | A string containing the name of the drive for a specified path
Description: | This method returns a string containing the name of the drive for a specified path.


GetExtensionName

GetExtensionName Method

Object: | FileManager
Syntax: | GetExtensionName ([in] Path)
Returns: | A string containing the file extension
Description: | This method returns the file extension. For example, if the complete path for a file is c:\temp\file.doc, this method returns doc.


GetFile

GetFile Method

Object: | FileManager
Syntax: | GetFile ([in] Filename)
Returns: | A file object
Description: | This method returns an individual file object. You can use the file object to perform many other file-specific operations.


GetFileName

GetFileName Method

Object: | FileManager
Syntax: | GetFileName ([in] Path)
Returns: | Returns the file name
Description: | This method returns the file name. For example if the complete path is c:\temp\file.doc, this method returns file.doc. If the Path argument does not end with the name of a file or folder, GetFileName returns an empty string.


GetFolder

GetFolder Method

Object: | FileManager
Syntax: | GetFolder ([in] DirectoryName)
Returns: | A Folder object
Description: | This method returns an individual Folder (directory) object. You can use the folder object to perform many other folder-specific operations. The DirectoryName must refer to a valid directory, not a file.


GetParentFolderName

GetParentFolderName Method

Object: | FileManager
Syntax: | GetParentFolderName ([in] Path)
Returns: | Returns a string containing the name of the parent folder of the file in a specified path.
Description: | This method returns the name of the parent folder of the file or folder in a specified path. For example if the complete path is c:\temp\file.doc, this method returns c:\temp. If there is no parent folder for the file or folder specified in the Path argument, the GetParentFolderName method returns a zero-length string.


GetSpecialFolder

GetSpecialFolder Method

Object: FileManager
Syntax: GetSpecialFolder ([in] folderspec)
Returns: A Folder object
Description: This method returns the special folder specified by the folderspec argument.

The folderspec argument can have any of the following values:

Constant | Value | Description
WindowsFolder | 0 | The Windows folder contains files installed by the Windows operating system.
SystemFolder | 1 | The System folder contains libraries, fonts, and device drivers.
TemporaryFolder | 2 | The Temp folder is used to store temporary files. Its path is found in the TMP environment variable.


GetTempName

GetTempName Method

Object: | FileManager
Syntax: | GetTempName
Returns: | Returns a randomly generated string that can be used as a temporary file or folder name.
Description: | The GetTempName method can be very useful in circumstances where it is necessary to generate a temporary file or folder. The GetTempName method requires no arguments.


ImportFromBlob

ImportFromBlob Method

Object: | FileManager
Syntax: | ImportFromBlob ([in] recordset("column-name"), [in] Destination)
Description: | This method extracts a Binary Large OBject (BLOB) from a database and writes to a file specified by the Destination argument. It overwrites the destination file if one with that name already exists.


INIDeleteKey

INIDeleteKey Method

Object: | FileManager
Syntax: | INIDeleteKey ([in] Filename, [in] Section, [in] Key)
Description: | This method deletes the specified key from the INI file.


INIDeleteSection

INIDeleteSection Method

Object: | FileManager
Syntax: | INIDeleteSection ([in] Filename, [in] Section)
Description: | This method deletes the specified section from the INI file.


INIReadBoolean

INIReadBoolean Method

Object: | FileManager
Syntax: | INIReadBoolean ([in] Filename, [in] Section, [in] Key, [in, optional] DefaultValue)
Returns: | True or False)
Description: | This method reads the value of the key from the specified section. If the key is not available, it returns the DefaultValue. If no default is specified, it returns False.


INIReadInteger

INIReadInteger Method

Object: | FileManager
Syntax: | INIReadInteger ([in] Filename, [in] Section, [in] Key, [in, optional] DefaultValue)
Returns: | Integer
Description: | This method reads the value of the key from the specified section. If the key is not available, it returns the Default Value. If no default is specified, it returns (-1).


INIReadString

INIReadString Method

Object: | FileManager
Syntax: | INIReadString ([in] Filename, [in] Section, [in] Key, [in, optional] DefaultValue)
Returns: | String
Description: | This method reads the value of the key from the specified section. If the key is not available, it returns the Default Value. If no default is specified, it returns "".


INIWriteBoolean

INIWriteBoolean Method

Object: | FileManager
Syntax: | INIWriteBoolean ([in] Filename, [in] Section, [in] Key, [in] Value)
Description: | This method writes the value of the key in the specified section.


INIWriteInteger

INIWriteInteger Method

Object: | FileManager
Syntax: | INIWriteInteger ([in] Filename, [in] Section, [in] Key, [in] Value)
Description: | This method writes the value of the key in the specified section.


INIWriteString

INIWriteString Method

Object: | FileManager
Syntax: | INIWriteString ([in] Filename, [in] Section, [in] Key, [in] Value)
Description: | This method writes the value of the key in the specified section.


LogonUser

LogonUser Method

Object: FileManager
Syntax: LogonUser ([in] DomainName, [in] Username, [in] Password, [in] LogonType)
Description: LogonUser is a very powerful method. While a given ASP page is executing, you can use it to switch user contexts, so the rest of the page executes as the specified user. To return to the previous user context, use the RevertToSelf method.

LogonUser calls cannot be nested. Every LogonUser must have a RevertToSelf before issuing another LogonUser.

LogonUser allows you to become a different user, perform some privileged file manipulations, and then return the previous security context of the execution thread.

Every LogonUser should have a corresponding RevertToSelf.

The password will be supplied in clear-text, so you must be particularly vigilant about either:
  • protecting the ASP source code from malicious users, or
  • using SSL to get a password from a user

LogonType can be one of the following:

Constant | Value | Description
saLogon_Interactive | 2 | Interactive Logon. This is the default.
saLogon_Network | 3 | Network Logon.
saLogon_Batch | 4 | Batch Logon.
saLogon_Service | 5 | Logon as a service.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\directory.

You may get an error in the following situation: When an application is run out of process, the IWAM_<Machine Name> account is used for authentication. IWAM_<Machine Name> does not have the right to "Act as part of the operating system."

To correct this, either:
  • Use SA-FileManager in process only.
Or:
  • Grant the IWAM_<Machine Name> account the right to "Act as part of the operating system":

    1. Open "User Manager for Domains" ("User Manager" if you are using a Workgroup network).
    2. Select User Rights from the Policies Menu.
    3. Enable the "Show advance user rights" checkbox.
    4. Select "Act as part of the Operating System" from the dropdown list of rights.
    5. Add the IWAM_<Machine Name> account to this list.
    6. Click OK and close the User Manager.


MoveFile

MoveFile Method

Object: | FileManager
Syntax: | MoveFile ([in] Source, [in] Destination, [in, optional] OverWrite)
Description: | This method moves, or renames, a file from the source to the destination location. By default, it overwrites the destination file. Set OverWrite to False to not overwrite the destination file.


MoveFolder

MoveFolder Method

Object: | FileManager
Syntax: | MoveFolder ([in] SourceDirectory, [in] DestinationDirectory)
Description: | This method moves, or renames, the source folder, sub-folders, and files to another location. If the folder already exists in the destination directory, the MoveFolder method fails.


OpenBinaryFile

OpenBinaryFile Method

Object: FileManager
Syntax: OpenBinaryFile ([in] Filename, [in] IOMode, [in] Create)
Returns: A BinaryStream object
Description: This method opens a file and returns a BinaryStream object so you can read and write the contents of the file.

You must specify the complete path of the file.

If Create is True, the file will be created. By default, it is False.

IOMode can be one of the following:

Constant | Value | Description
ForReading | 1 | To read the file. This is the default.
ForWriting | 2 | To write to the file.
ForAppending | 8 | To append to the file.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\directory.


OpenTextFile

OpenTextFile Method

Object: FileManager
Syntax: OpenTextFile ([in] Filename, [in] IOMode, [in] Create, [in] Format)
Returns: A TextStream object
Description: This method opens a file and returns a TextStream object so you can read and write the contents of the file.

You must specify the complete path of the file.

If Create is True, the file will be created. By default, it is False.

IOMode can be one of the following:

Constant | Value | Description
ForReading | 1 | To read the file. This is the default.
ForWriting | 2 | To write to the file.
ForAppending | 8 | To append to the file.

Format can be one of the following:

Constant | Value | Description
TristateTrue | -1 | Open the file as UNICODE.
TristateFalse | 0 | Open the file as ANSI. This is the default.
TristateUseDefault | -2 | Examine the file to determine if it should be opened as UNICODE or ANSI, and open the file appropriately.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\directory.


RegisterDLL

RegisterDll Method

Object: | FileManager
Syntax: | RegisterDLL ([in] Filename, [in, optional] Register)
Description: | This method registers a DLL in the system registry, similar to the command-line REGSVR32 program. The filename must contain the entire valid path, and must correspond to a self-registering DLL. If Register is True, the DLL will be registered. This is the default. If Register is False, the DLL will be unregistered. You can disable this method by using a registry setting. See Disabling SA-FileUpFeatures . By default, it is enabled.


RevertToSelf

RevertToSelf Method

Object: | FileManager
Syntax: | RevertToSelf ()
Description: | RevertToSelf restores the security context prior to executing LogonUser method. Every LogonUser should have a corresponding RevertToSelf.


FileManager Properties

CurrentUser
Drives
ProcessUser


CurrentUser

CurrentUser Property

Object: | FileManager
Syntax: | CurrentUser
Type: | String
Read/Write: | Read Only
Description: | This property returns the currently impersonated user of the thread. This is very useful if you are using Active Server Pages and testing various authentication mechanisms. It will report the ComputerName\AccountName currently in use, such as WEBSERVER1\IUSR_WEBSERVER1. If, for example, NT Challenge / Response Authentication is currently in use, it will return DomainName\Username such as COMPANY1\JOE. If you are using LogonUser or RevertToSelf, this is also a useful means of determining that the login in use is what you expect it to be.


Drives

Drives Property

Object: | FileManager
Syntax: | Drives
Type: | A collection of Drive objects
Read/Write: | Read Only
Description: | This property returns a collection of all drives on the current system.


ProcessUser

ProcessUser Property

Object: | FileManager
Syntax: |
Type: | String
Read/Write: | Read Only
Description: | This property returns the current process's user name in DOMAIN\USER format.


The BinaryStream Object

The BinaryStream object works with binary data. Use it to manipulate and administer binary data or information about binary data.

BinaryStream Methods

BinaryStream Properties


BinarySteam Methods

Close
Fill
Read
ReadAll
ReadVar
ReadVarAll
Skip
Write


Close

Close Method

Object: | BinaryStream
Syntax: | Close ()
Description: | This method closes the currently open file.


Fill

Fill Method

Object: | BinaryStream
Syntax: | Fill ([in] Byte, [in] numBytes)
Description: | From the current location in the file, this method fills the file with specified byte a total of 'numBytes' times.


Read

Read Method

Object: | BinaryStream
Syntax: | Read ([in] numBytes)
Returns: | An array of binary characters
Description: | From the current location in the file, this method reads numBytes from the file and returns an array of binary characters. In Automation terms, this is a VT_UI1 | VT_ARRAY type. You can also check the AtEndOfStream property to determine if you've reached the end of file.


ReadAll

ReadAll Method

Object: BinaryStream
Syntax: ReadAll ()
Returns: An array of binary characters
Description: This method reads the entire contents of the file into an array of binary characters. In Automation terms, this is a VT_UI1 | VT_ARRAY type.

Note: For performance purposes, it is not recommended that you read very large files into memory on a Web Server, as this may significantly tax server resources.


ReadVar

ReadVar Method

Object: BinaryStream
Syntax: ReadVar (long numBytes)
Returns: An array of variants
Description: From the current location in the file, this method reads numBytes from the file and returns an array of variants. This allows you to manipulate individual bytes within a script.

Note: For performance purposes, it is not recommended that you read large files into memory on a Web Server, as this may significantly tax server resources.

Example:

Set oFM = CreateObject("SoftArtisans.FileManager") Set oBS = oFM.OpenBinaryFile(
      fileName ) dim a dim b Do While Not oBS.AtEndOfStream a = oBS.ReadVar(5) ' You can
      go through each single element b = Chr(a(1)) loop oBS.Close Set oFM = nothing


ReadVarAll

ReadVarAll Method

Object: BinaryStream
Syntax: ReadVarAll ()
Returns: An array of variants
Description: This method reads the entire contents of the file into an array of variants. This allows you to manipulate individual bytes within a script.

Note: For performance purposes, it is not recommended that you read large files into memory on a Web Server, as this may significantly tax server resources.

Example:

Set oFM = CreateObject("SoftArtisans.FileManager") Set oBS = oFM.OpenBinaryFile(
      fileName ) dim a dim b a = oBS.ReadVarAll b = Chr(a(1)) oBS.Close Set oFM = nothing


Skip

Skip Method

Object: | BinaryStream
Syntax: | Skip ([in] numBytes)
Description: | This method moves the file cursor ahead the specified number of bytes.


Write

Write Method

Object: | BinaryStream
Syntax: | Write ([in] string)
Description: | This method writes the specified binary string to the file at the current file cursor location.


BinaryStream Properties

AtEndOfStream


AtEndOfStream

AtEndofStream Property

Object: | BinaryStream
Syntax: | AtEndOfStream ()
Type: | Boolean
Description: | This property is True if the file cursor is at the end of the file. It is False if the cursor is at the beginning or middle of the file.


The Drive Object

The Drive object allows you to look at hard drives and virtual drives. The Drive object can provide a listing of all drives on the server. It cal also provide a means of getting drive information from the source machine or server.

The Drive Object does not contain methods, only properties.

Drive Properties


Drive Methods

The Drive Object does not contain methods, only properties.


Drive Properties

All properties are read-only unless otherwise noted.

AvailableSpace
DriveLetter
DriveType
FileSystem
FreeSpace
IsReady
Path
RootFolder
SerialNumber
ShareName
TotalSize
VolumeName (Read / Write)


AvailableSpace

AvailableSpace Property

Object: | Drive
Syntax: | AvailableSpace ()
Type: | Double precision floating point
Read/Write: | Read only
Description: | This property returns the number of bytes on the drive available to this user. This is usually the same as the FreeSpace property, except when user quotas are in use.


DriveLetter

DriveLetter Property

Object: | Drive
Syntax: | DriveLetter ()
Type: | String
Read/Write: | Read Only
Description: | This property returns the letter of the current drive, e.g., Cfor the C: drive.


DriveType

DriveType Property

Object: Drive
Syntax: DriveType ()
Type: String
Read/Write: Read Only
Description: This property returns the type of the current drive.

DriveType can be one of the following:

Constant | Value | Description
Unknown | 0 | Unable to determine drive type.
Removable | 1 | Removable drive, i.e., floppy.
Fixed | 2 | Non-removable drive, i.e., regular hard disk.
Remote | 3 | Network mounted drive or share.
CDRom | 4 | Drive is a CD-ROM.
RAMDisk | 5 | Drive is a volatile disk RAM.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\directory.


FileSystem

FileSystem Property

Object: | Drive
Syntax: | FileSystem ()
Type: | String
Read/Write: | Read Only
Description: | This property returns the FileSystem of the specified drive, e.g., FAT, NTFS, etc.


FreeSpace

FreeSpace Property

Object: | Drive
Syntax: | FreeSpace ()
Type: | Double precision floating point
Read/Write: | Read Only
Description: | This property returns the number of unused bytes on the drive for all users. This is usually the same as the AvailableSpace property, except when user quotas are in use.


IsReady

IsReady Property

Object: | Drive
Syntax: | IsReady ()
Type: | Boolean
Read/Write: | Read Only
Description: | This property returns True if the drive is ready for access. It returns False if the drive is unavailable.


Path

Path Property

Object: | Drive
Syntax: | Path ()
Type: | String
Read/Write: | Read Only
Description: | This property returns the path of the current drive, e.g., C:.


RootFolder

RootFolder Property

Object: | Drive
Syntax: | RootFolder ()
Type: | A Folder object
Read/Write: | Read Only
Description: | This property returns a Folder object that corresponds to the root folder of the current drive, e.g., C:\.


SerialNumber

SerialNumber Property

Object: | Drive
Syntax: | SerialNumber ()
Type: | String
Read/Write: | Read Only
Description: | This property returns the serial number of the current drive, if available.


ShareName

ShareName Property

Object: | Drive
Syntax: | ShareName ()
Type: | String
Read/Write: | Read Only
Description: | This property returns the name of the share for the current drive in UNC format, e.g., \\SERVER1\SHARE1.


TotalSize

TotalSize Property

Object: | Drive
Syntax: | TotalSize ()
Type: | Double precision floating point
Read/Write: | Read Only
Description: | This property returns the size of the current drive, in bytes.


VolumeName

VolumeName Property

Object: | Drive
Syntax: | VolumeName ()
Type: | String
Read/Write: | Read/Write
Description: | This property returns or sets the name of the current volume. You must have sufficient privileges to change the name of a volume.


The File Object

Use the File object for file management. You can use it to manage files, look at attributes of files, set permissions for files, and to move files.

File Methods

File Properties


File Methods

AllowAccess
Copy
Decrypt
Delete
DenyAccess
Encrypt
Move
OpenAsBinaryStream
OpenAsTextStream
RevokeAllowance
OrderPermissions
RevokeDenial


AllowAccess

AllowAccess Method

Object: File
Syntax: AllowAccess ([in] AccountName, [in] Permissions)
Description: This method creates an Access Control Entry (ACE) for the current file that allows specific access.

The AccountName must resolve to a valid NT account in the domain.

The Permissions can have any of the following values or any logical combination of the following values:

Constant | Value | Description
saNoAccess | 1 | All Access is denied.
saRead | 2 | The file can be read.
saWrite | 4 | The file can be written.
saExecute | 8 | The file can be executed.
saDelete | 16 | The file can be deleted.
saPermissions | 32 | Permissions on the file can be changed.
saOwner | 64 | Allows taking ownership of the file.
saFull | 126 | Allows all of the above permissions (except NoAccess).
saReadExecute (Windows 2000 only) | 512 | The file can be read and executed.
saModify (Windows 2000 only) | 1024 | The file can be modified.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\FileManagerSamplesdirectory.


Copy

Copy Method

Object: | File
Syntax: | Copy ([in] Filename, [in, optional] OverWrite)
Description: | This method copies the current file to another location. By default, it overwrites the destination file. To not overwrite the destination file, set OverWrite to False.


Decrypt

Decrypt Method

Object: File
Syntax: objFile.Decrypt ([in]OutFileName, [in]Password, [in, optional, defaultvalue(1)] saEncType)
Description:

This method decrypts the current file and saves the result to the location specified by the OutFileNameparameter.

FileManager allows you to select either TwoFish or RSAencryption. TwoFish encryption is 128-bit. RSA encryption is either 40-bit or 128-bit, depending on the system. To determine whether the system supports 128-bit encryption, check Internet Explorer's "About" (in IE's Help menu).

Decrypt Parameters
OutFileName | FileManager will save the decrypted file to this location
Password | The password set by EncryptFile or Encrypt. If the password is incorrect, the file will be saved as OutFileNamebut the decryption will fail.
saEncType The encryption type, which may be either TwoFish encryption, or CryptoAPI. Assign saEncTypeby name or number:

1 | SARSA
2 | SATWOFISH
3 | SARSAHIGH
4 | SARSALOW


Delete

Delete Method

Object: | File
Syntax: | Delete ([in, optional] Force)
Description: | This method deletes the current file. If Force is True, read-only files are also deleted. By default, Force is False.


DenyAccess

DenyAccess Method

Object: File
Syntax: DenyAccess ([in] AccountName, [in] Permissions)
Description: This method creates an Access Control Entry (ACE) for the current file that denies specific access rights.

The AccountName must resolve to a valid NT account in the domain.

The Permissions can have any of the following values or any logical combination of the following values:

Constant | Value | Description
saNoAccess | 1 | All Access is denied.
saRead | 2 | The file can be read.
saWrite | 4 | The file can be written.
saExecute | 8 | The file can be executed.
saDelete | 16 | The file can be deleted.
saPermissions | 32 | Permissions on the file can be changed.
saOwner | 64 | Allows taking ownership of the file.
saFull | 126 | Allows all of the above permissions (except NoAccess).
saReadExecute (Windows 2000 only) | 512 | The file can be read and executed.
saModify (Windows 2000 only) | 1024 | The file can be modified.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\FileManagerSamplesdirectory.


Encrypt

Encrypt Method

Object: File
Syntax: objFile.Encrypt ([in] OutFilename, [in] Password, [in, optional, defaultvalue(1)] saEncType)
Description:

This method encrypts the current file and saves the result to the location specified by the OutFileNameparameter. Use the Decrypt method to decrypt the file.

FileManager allows you to select either TwoFish or RSAencryption. TwoFish encryption is 128-bit. RSA encryption is either 40-bit or 128-bit, depending on the system. To determine whether the system supports 128-bit encryption, check Internet Explorer's "About" (in IE's Help menu).

Encrypt Parameters
OutFileName FileManager will save the encrypted file to this location
Password Use this password to decrypt the file with either DecryptFile or Decrypt.

Important! Remember the password. You will not be able to recover the file without it.
saEncType The encryption type, which may be either RSA Encryption or TwoFish encryption. Assign saEncTypeby name or number:

1 | SARSA
2 | SATWOFISH
3 | SARSAHIGH
4 | SARSALOW


Move

Move Method

Object: | File
Syntax: | Move ([in] Filename, [in, optional] OverWrite)
Description: | This method moves, or renames, the current file to another location. By default, it overwrites the destination file. To not overwrite the destination file, set OverWrite to False.


OpenAsBinaryStream

OpenAsBinaryStream Method

Object: File
Syntax: OpenAsBinaryStream ([in] IOMode)
Returns: A BinaryStream object
Description: This method opens a file and returns a BinaryStream object so that you can read and write the contents of the file.

IOMode can be one of the following:

Constant | Value | Description
ForReading | 1 | To read the file. This is the default.
ForWriting | 2 | To write to the file.
ForAppending | 8 | To append to the file.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\directory.


OpenAsTextStream

OpenAsTextStream Method

Object: File
Syntax: OpenAsTextStream ([in] IOMode, [in] Format)
Returns: A TextStream object
Description:

This method opens a file and returns a TextStream object so you can read and write the contents of the file.

IOMode can be one of the following:

Constant | Value | Description
ForReading | 1 | To read the file. This is the default.
ForWriting | 2 | To write to the file.
ForAppending | 8 | To append to the file.

Format can be one of the following:

Constant | Value | Description
TristateTrue | -1 | Open the file as UNICODE.
TristateFalse | 0 | Open the file as ANSI. This is the default.
TristateUseDefault | -2 | Examine the file to determine if it should be opened as UNICODE or ANSI, and open the file appropriately.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\directory.


OrderPermissions

OrderPermissions Method

Object: | File
Syntax: | OrderPermissions ()
Description: | This method correctly orders the ACEs in the file's DACL. It does not need to be called after AllowAccess() or DenyAccess(), but it can be called by the client to order a DACL which has been modified externally. The complete SA-FileManagersource code is available for purchase from http://www.SoftArtisans.com.


RevokeAllowance

RevokeAllowance Method

Object: | File
Syntax: | RevokeAllowance ([in] AccountName)
Description: | This method deletes all allowed Access Control Entries (ACE) of the specified account for the current file. In other words, if a specific account has been granted an affirmative ACE on this file, this method will remove that affirmation. The AccountName must resolve to a valid NT account in the domain.


RevokeDenial

RevokeDenial Method

Object: | File
Syntax: | RevokeDenial ([in] AccountName)
Description: | This method deletes all denied Access Control Entries (ACE) of the specified account for the current file. In other words, if a specific account has been granted an negative ACE on this file (i.e., "you are not allowed to write to this file"), this method will remove that denial. The AccountName must resolve to a valid NT account in the domain.


prog_ref_file_properties

Accessible
Attributes
Checksum
DateCreated
DateLastAccessed
DateLastModified
Drive
FileSystem
ImageColor Property
ImageHeight Property
ImageWidth Property
MimeType
Name
Owner
ParentFolder
Path
Permissions
ShortName
ShortPath
Size
Type


Accessible

Accessible Property

Object: File
Syntax: objFile.Accessible
Type: Boolean
Read/Write: Read Only
Description:

This property returns TRUE if the current security context allows access to information about the file (such as its size).

Note: To prevent errors, check the value of Accessiblebefore trying to access file information.


Attributes

Attributes Property

Object: File
Syntax: Attributes
Type: Long Integer
Read/Write: Read/Write (depending on the attribute)
Description: This property returns the file attributes listed below.

The attributes can have any of the following values or any logical combination of the following values:

Constant | Value | Description
saNormal | 0 | Normal file. No attributes are set.
saReadOnly | 1 | Read-only file. Attribute is read/write.
saHidden | 2 | Hidden file. Attribute is read/write.
saSystem | 4 | System file. Attribute is read/write.
saVolume | 8 | Disk drive volume label. Attribute is read-only.
saDirectory | 16 | Folder or directory. Attribute is read-only.
saArchive | 32 | File has changed since last backup. Attribute is read/write.
saAlias | 64 | Link or shortcut. Attribute is read-only.
saCompressed | 2048 | Compressed file. Attribute is read-only.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\FileManagerSamplesdirectory.


Checksum

Object: File
Syntax: File.Checksum
Type: String
Read/Write: Read only
Description:

The Checksum property returns a string representing the specified file's MD5 hash. You can use this value to verify that a file was not corrupted (during an upload, for example), by comparing before and after MD5 hashes.

Use FileManager's Checksum property to generate an MD5 hash on the client before uploading or after downloading with SoftArtisans FileUp. Then, compare FileManager's MD5 hash with the MD5 hash that FileUp generated on the server.

See Also: FileUp Checksum Property
Example:
<!-- Generate a file's MD5 hash:--> <script language="javascript">
            function getMD5(file) { var hash; var file; file_mgr = new ActiveXObject("SoftArtisans.FileManager");
            file = file_mgr.GetFile(file) hash = file.Checksum return hash } </script>
            <!-- You can use the generated hash to populate a form element:--><input type=button value="Generate Checksum" onclick="Checksum.value = getMD5(FILE1.value)">
            Checksum: <input type=text name=Checksum size=40>


DateCreated

DateCreated Property

Object: | File
Syntax: | DateCreated
Type: | Date
Read/Write: | Read Only
Description: | This property returns the date and time that the specified file was created.


DateLastAccessed

DateLastAccessed Property

Object: | File
Syntax: | DateLastAccessed
Type: | Date
Read/Write: | Read Only
Description: | This property returns the date that the specified file was created. If used with an NTFS partition, the time is also returned.


DateLastModified

DateLastModified Property

Object: | File
Syntax: | DateLastModified
Type: | Date
Read/Write: | Read Only
Description: | This property returns the date and time that the specified file was last modified.


Drive

Drive Property

Object: | File
Syntax: | Drive
Type: | A Drive object
Read/Write: | Read Only
Description: | This property returns a Drive object that corresponds to the drive where this file is located.


FileSystem

FileSystem Property

Object: File
Syntax: objFile.FileSystem
Type:

saFileSystemType

saFileSystemType
Constant | Value | Description
SAFILESYSTEM_NTFS | 1 | NTFS drive.
SAFILESYSTEM_FAT32 | 2 | FAT32 drive.
SAFILESYSTEM_FAT | 3 | Other FAT type.
Read/Write: Read Only
Description:

This property returns the file system of the drive of the current file.

Note: Security information is only applicable on NTFS drives.


ImageColor

ImageColor Property

Object: File
Syntax: objFile.ImageColor
Type: Long
Read/Write: Read Only
Description: Returns the color count of GIF, JPEG, BMP, and PNG format image files.
Example:
<% Set objFileManager = Server.CreateObject("Softartisans.FileManager") Path
            = Server.MapPath("image.gif") Set File = objFileManager.GetFile(Path) Response.Write
            "<Center><Table border=1 CELLSPACING=2 CELLPADDING=5>" Response.Write
            "<TR><TH colspan=2>File name = " & File.Name & "</TH><TR>"
            Response.Write "<TR><TD>Image Height</TD><TD>" & File.ImageHeight
            & "</TD></TR>" Response.Write "<TR><TD>Image Width</TD><TD>"
            & File.ImageWidth & "</TD></TR>" Response.Write "<TR><TD>Image
            Color</TD><TD>" & File.ImageColor & "</TD></TR>"
            Response.Write "<TR><TD colspan=2><IMG src='" & Path & "'></TD></TR>"
            Response.Write "</Table></Center>" %>


ImageHeight

ImageHeight Property

Object: File
Syntax: objFile.ImageHeight
Type: Long
Read/Write: Read Only
Description: Returns the height of an image. ImageHeight can read the height of GIF, JPEG, BMP, and PNG format images.
Example:
<% Set objFileManager = Server.CreateObject("Softartisans.FileManager") Path
            = Server.MapPath("image.gif") Set File = objFileManager.GetFile(Path) Response.Write
            "<Center><Table border=1 CELLSPACING=2 CELLPADDING=5>" Response.Write
            "<TR><TH colspan=2>File name = " & File.Name & "</TH><TR>"
            Response.Write "<TR><TD>Image Height</TD><TD>" & File.ImageHeight& "</TD></TR>" Response.Write "<TR><TD>Image Width</TD><TD>"
            & File.ImageWidth & "</TD></TR>" Response.Write "<TR><TD>Image
            Color</TD><TD>" & File.ImageColor & "</TD></TR>" Response.Write
            "<TR><TD colspan=2><IMG src='" & Path & "'></TD></TR>"
            Response.Write "</Table></Center>" %>


ImageWidth

ImageWidth Property

Object: File
Syntax: objFile.ImageWidth
Type: Long
Read/Write: Read Only
Description: Returns the width of an image. ImageWidth can read the width of GIF, JPEG, BMP, and PNG format images.
Example:
<% Set objFileManager = Server.CreateObject("Softartisans.FileManager") Path
            = Server.MapPath("image.gif") Set File = objFileManager.GetFile(Path) Response.Write
            "<Center><Table border=1 CELLSPACING=2 CELLPADDING=5>" Response.Write
            "<TR><TH colspan=2>File name = " & File.Name & "</TH><TR>"
            Response.Write "<TR><TD>Image Height</TD><TD>" & File.ImageHeight
            & "</TD></TR>" Response.Write "<TR><TD>Image Width</TD><TD>"
            & File.ImageWidth & "</TD></TR>" Response.Write "<TR><TD>Image
            Color</TD><TD>" & File.ImageColor & "</TD></TR>" Response.Write
            "<TR><TD colspan=2><IMG src='" & Path & "'></TD></TR>"
            Response.Write "</Table></Center>" %>


MimeType

MimeType Property

Object: | File
Syntax: | MimeType
Type | String
Read/Write: | Read Only
Description: | This property returns the MIME Type of the specified file. For example, a file with an extension of ".txt" will have a MIME Type of "text/plain". This can be useful when using SA-FileUp's.TransferFile property to set the MIME type appropriately. The MIME Type is also sometimes known as the ContentType, as in the IIS 4 or later documentation.


Name

Name Property

Object: | File
Syntax: | Name
Type: | String
Read/Write: | Read/Write
Description: | This property returns or sets the name of the specified file.


Owner

Owner Property

Object: | File
Syntax: | Owner
Type: | String
Read/Write: | Read/Write
Description: | This property returns or sets the owner of the specified file. It is only possible to take ownership of a file. You cannot arbitrarily set ownership of a file to someone else. To take ownership of a file, you must execute LogonUser first, and set the owner of the file to yourself.


ParentFolder

ParentFolder Property

Object: | File
Syntax: | ParentFolder
Type: | String
Read/Write: | Read Only
Description: | This property returns the parent folder of the specified file.


Path

Path Property

Object: | File
Syntax: | Path
Type: | String
Read/Write: | Read Only
Description: | This property returns the path for the specified file.


Permissions

Permissions Property

Object: | File
Syntax: | Permissions
Type: | A PermItem collection for the file
Read/Write: | Read Only
Description: | This property contains a PermItem collection for the file.


ShortName

ShortName Property

Object: | File
Syntax: | ShortName
Type: | String
Read/Write: | Read Only
Description: | This property returns the short name of the specified file. The ShortName method uses the 8.3 naming convention.


ShortPath

ShortPath Property

Object: | File
Syntax: | ShortPath
Type: | String
Read/Write: | Read Only
Description: | This property returns the short path of the specified file. The ShortPath method uses the 8.3 naming convention.


Size

Size Property

Object: | File
Syntax: | Size
Type: | Long Integer
Read/Write: | Read Only
Description: | This property returns the size of the specified file in bytes.


Type

Type Property

Object: | File
Syntax: | Type
Type: | String
Read/Write: | Read Only
Description: | This property returns a description of a specified file. For example, for files ending in .HTM, "Microsoft HTML Document 4.0" may be returned.


The Folder Object

The Folder object represents a single folder. You can use it to manage folders, look at attributes of folders, set permissions for folders, and to move folders.

Methods Properties


Folder Methods

AllowAccess
Copy
CreateBinaryFile
CreateTextFile
Delete
DenyAccess
Move
OrderPermissions
RevokeAllowance
RevokeDenial


AllowAccess

AllowAccess Method

Object: Folder
Syntax: AllowAccess ([in] AccountName, [in] Permissions [PermissionType])
Description: This method creates an Access Control Entry (ACE) for the current folder that allows specific access.

The AccountName must resolve to a valid NT account in the domain.

The Permissions can have any of the following values or any logical combination of the following values:

Constant | Value | Description
saNoAccess | 1 | All Access is denied.
saRead | 2 | The file can be read.
saWrite | 4 | The file can be written.
saExecute | 8 | The file can be executed.
saDelete | 16 | The file can be deleted.
saPermissions | 32 | Permissions on the file can be changed.
saOwner | 64 | Allows taking ownership of the file.
saFull | 126 | Allows all of the above permissions (except NoAccess).
saList (Windows 2000 only) | 256 | Folder content list can be viewed.
saReadExecute (Windows 2000 only) | 512 | The file can be read and executed.
saModify (Windows 2000 only) | 1024 | The file can be modified.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\FileManagerSamplesdirectory.

PermissionType is an optional parameter. By default, its value is 3. If set to 1, permission is for files. If set to 2, permission is for directories. If 3, permission is for both files and directories.


CreateBinaryFile

CreateBinaryFile Method

Object: | Folder
Syntax: | CreateBinaryFile ([in] Name, [in] OverWrite)
Returns: | A BinaryStream
Description: | This method creates a new file in the current folder and returns a BinaryStream object so you can read and write the contents of the file. If OverWrite is True, and the file already exists, it will be overwritten. It is True by default.


CreateTextFile

CreateTextFile Method

Object: | Folder
Syntax: | CreateTextFile ([in] Name, [in] OverWrite, [in] Unicode)
Returns: | A TextStream object
Description: | This method creates a new file in the current folder and returns a TextStream object so you can read and write the contents of the file. If OverWrite is True, and the file already exists, it will be overwritten. It is True by default. If Unicode is True, the file will be created in Unicode format. It is False by default.


Copy

Copy Method

Object: | Folder
Syntax: | Copy ([in] DestinationDirectory, [in, optional] OverWrite)
Description: | This method copies the current folder, sub-folders and files to another location. If OverWrite is True, all similarly named files will be overwritten. It is True by default. Set OverWrite to False to not overwrite any existing destination files.


Delete

Delete Method

Object: | Folder
Syntax: | Delete ([in] Force)
Description: | This method deletes the current folder, including all sub-folders and files. If Force is True, then read-only files will be deleted as well. By default, Force is False.


DenyAccess

DenyAccess Method

Object: Folder
Syntax: DenyAccess ([in] AccountName, [in] Permissions)
Description: This method creates an Access Control Entry (ACE) for the current folder that denies specific access rights.

The AccountName must resolve to a valid NT account in the domain.

The Permissions can have any of the following values or any logical combination of the following values:

Constant | Value | Description
saNoAccess | 1 | All Access is denied.
saRead | 2 | The file can be read.
saWrite | 4 | The file can be written.
saExecute | 8 | The file can be executed.
saDelete | 16 | The file can be deleted.
saPermissions | 32 | Permissions on the file can be changed.
saOwner | 64 | Allows taking ownership of the file.
saFull | 126 | Allows all of the above permissions (except NoAccess).
saReadExecute (Windows 2000 only) | 512 | The file can be read and executed.
saModify (Windows 2000 only) | 1024 | The file can be modified.

These constants can be found using the IIS 4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\FileManagerSamplesdirectory.


Move

Move Method

Object: | Folder
Syntax: | Move ([in] DestinationDirectory)
Description: | This method moves, or renames, the current folder, sub-folders and files to another location. If the folder already exists in the destination directory, the Move method fails.


OrderPermissions

OrderPermissions Method

Object: | Folder
Syntax: | OrderPermissions ()
Description: | This method correctly orders the ACEs in the folder's DACL. It does not need to be called after AllowAccess() or DenyAccess(), but it can be called by the client to order a DACL which has been modified externally. The complete FileManagersource code is available for purchase from http://www.SoftArtisans.com.


RevokeAllowance

RevokeAllowance Method

Object: | Folder
Syntax: | RevokeAllowance ([in] AccountName)
Description: | This method deletes all allowed Access Control Entries (ACE) of the specified account for the current folder. In other words, if a specific account has been granted an affirmative ACE on this file, this method will remove that affirmation. The AccountName must resolve to a valid NT account in the domain.


RevokeDenial

RevokeDenial Method

Object: | Folder
Syntax: | RevokeDenial ([in] AccountName)
Description: | This method deletes all denied Access Control Entries (ACE) of the specified account for the current folder. In other words, if a specific account has been granted a negative ACE on this folder (i.e., "you are not allowed to write to this folder"), this method will remove that denial. The AccountName must resolve to a valid NT account in the domain.


Folder Properties

Accessible
Attributes
DateCreated
DateLastAccessed
DateLastModified
Drive
Files
FileSystem
IsRootFolder
Name
Owner
ParentFolder
Path
Permissions
SearchWildCard
ShortName
ShortPath
Size
SubFolders
Type


Accessible

Accessible Property

Object: Folder
Syntax: objFolder.Accessible
Type: Boolean
Read/Write: Read Only
Description:

This property returns TRUE if the current security context allows access to information about the folder (such as its size).

Note: To prevent errors, check the value of Accessiblebefore trying to access folder information.


Attributes

Attributes Property

Object: Folder
Syntax: Attributes
Type: Long Integer
Read/Write: Read/Write (depending on the attribute)
Description: Returns the file/folder attributes listed below.

The Attributes can have any of the following values or any logical combination of the following values:

Constant | Value | Description
saNormal | 0 | Normal directory. No attributes are set.
saReadOnly | 1 | Read-only directory. Attribute is read/write.
saHidden | 2 | Hidden directory. Attribute is read/write.
saSystem | 4 | System directory. Attribute is read/write.
saVolume | 8 | Disk drive volume label. Attribute is read-only.
saDirectory | 16 | Folder or directory. Attribute is read-only.
saArchive | 32 | Directory has changed since last backup. Attribute is read/write.
saAlias | 64 | Link or shortcut. Attribute is read-only.
saCompressed | 2048 | Compressed directory. Attribute is read-only.

These constants can be found using the IIS4 or later TypeLibrary feature, or by viewing the vbFileManagerInclude.asp file contained in the .\Samples\FileManagerSamplesdirectory.


DateCreated

DateCreated Property

Object: | Folder
Syntax: | DateCreated
Type: | Date
Read/Write: | Read Only
Description: | This property returns the date and time that the specified folder was created.


DateLastAccessed

DateLastAccessed Property

Object: | Folder
Syntax: | DateLastAccessed
Type: | Date
Read/Write: | Read Only
Description: | This property returns the date that the specified folder was created. If you use this property with an NTFS partition, the time is also returned.


DateLastModified

DateLastModified Property

Object: | Folder
Syntax: | DateLastModified
Type: | Date
Read/Write: | Read Only
Description: | This property returns the date and time that the specified folder was last modified.


Drive

Drive Property

Object: | Folder
Syntax: | Drive
Type: | A Drive object
Read/Write: | Read Only
Description: | This property returns a Drive object that corresponds to the drive where this folder is located.


Files

Files Property

Object: | Folder
Syntax: | Files
Type: | A collection of file objects
Read/Write: | Read Only
Description: | This property returns a collection of file objects. The collection is determined by the SearchWildCard property. You can use the collection of file objects to perform many other file-specific operations.


FileSystem

FileSystem Property

Object: Folder
Syntax: FileSystem
Type: SAFileSystemType
Read/Write: Read Only
Description: This property returns the file system of the drive of the current folder.

Note: Security information is only applicable on NTFS drives.

SAFileSystemType
Constant | Value | Description
SAFILESYSTEM_NTFS | 1 | NTFS drive.
SAFILESYSTEM_FAT32 | 2 | FAT32 drive.
SAFILESYSTEM_FAT | 3 | Other FAT type.


IsRootFolder

IsRootFolder Property

Object: | Folder
Syntax: | IsRootFolder
Type: | Boolean
Read/Write: | Read Only
Description: | This property returns True if the specified folder is the root folder, or False if it is not.


Name

Name Property

Object: | Folder
Syntax: | Name
Type: | String
Read/Write: | Read/Write
Description: | This property returns or sets the name of the specified folder.


Owner

Owner Property

Object: | Folder
Syntax: | Owner
Type: | String
Read/Write: | Read/Write
Description: | This property returns or sets the owner of the specified folder. It is only possible to take ownership of a folder or file. You cannot arbitrarily set ownership of a folder or file to someone else. To take ownership of a folder or file, you must execute LogonUser first, and set the owner of the folder or file to yourself.


ParentFolder

ParentFolder Property

Object: | Folder
Syntax: | ParentFolder
Type: | String
Read/Write: | Read Only
Description: | This property returns the parent folder of the current folder.


Path

Path Property

Object: | Folder
Syntax: | Path
Type: | String
Read/Write: | Read Only
Description: | This property returns the path for the specified folder.


Permissions

Permissions Property

Object: | Folder
Syntax: | Permissions
Type: | A PermItem collection for the folder
Read/Write: | Read Only
Description: | This property contains a PermItem collection for the folder.


SearchWildCard

SearchWildCard Property

Object: | Folder
Syntax: | SearchWildCard
Type: | String
Read/Write: | Read/Write
Description: | This property sets the wildcard search pattern for the .Subfolders or .Files collections. This property uses the standard Microsoft wildcard patterns, such as *.*, *.txt, h*.*, etc.
Example: | The following code will list all files in the C:\WinNT that have a bmp extension.
dim oFM dim oFolder dim oFile Set oFM = CreateObject("SoftArtisans.FileManager")
      Set oFolder = oFM.GetFolder("C:\WinNT") oFolder.SearchWildCard = "*.bmp" For Each
      oFile in oFolder.Files Response.Write oFile.Name & "<br>" Next


ShortName

ShortName Property

Object: | Folder
Syntax: | ShortName
Type: | String
Read/Write: | Read Only
Description: | This property returns the short name of the specified folder. The ShortName property uses the 8.3 naming convention.


ShortPath

ShortPath Property

Object: | Folder
Syntax: | ShortPath
Type: | String
Read/Write: | Read Only
Description: | This property returns the short path of the specified folder. The ShortPath property uses the 8.3 naming convention.


Size

Size Property

Object: Folder
Syntax: Size
Type: Long Integer
Read/Write: Read Only
Description: This property returns the size of the current folder and all sub-folders.

Note: This is potentially a very expensive method call, as the only way to reliably determine the size of all sub-folders involves recursively examining each sub-folder individually.


SubFolders

Subfolders Property

Object: | Folder
Syntax: | Subfolders ()
Returns: | A collection of Folder objects
Description: | This property returns a collection of Folder objects. The collection is determined by the SearchWildCard property. You can use the collection of Folder objects to perform many other folder-specific operations. You can also use the subfolder collection to recursively walk a complete directory tree. See the example in the .\Samples\FileManagerSamples directory.


Type

Type Property

Object: | Folder
Syntax: | Type
Type: | String
Read/Write: | Read Only
Description: | This property returns a description of a specified folder. For example, for an ordinary file folder, "File Folder" may be returned.


The TextStream Object

The TextStream object works with text data. Use it to manipulate and administer text data. It is similar to the Microsoft Scripting.FileSystem object.

Methods Properties


TextSteam Methods

Close
Read
ReadAll
ReadLine
Skip
SkipLine
Write
WriteBlankLines
WriteLine


Close

Close Method

Object: | TextStream
Syntax: | Close ()
Description: | This method closes the currently open file.


Read

Read Method

Object: | TextStream
Syntax: | Read ([in] numBytes)
Returns: | An array of text characters
Description: | This method reads numBytes from the file, starting at the current location, and returns an array of text characters. A conversion is attempted from any binary characters to legible text characters. In Automation terms, this is a VT_BSTRtype. You can also check the AtEndOfStream property to determine if you've reached the end of file.


ReadAll

ReadAll Method

Object: TextStream
Syntax: ReadAll ()
Returns: An array of text characters
Description: This method reads the entire contents of the file into an array of text characters. In Automation terms, this is a VT_BSTR type.

Note: For performance purposes, it is not recommended to read very large files into memory on a web server, as this may significantly tax server resources.


ReadLine

ReadLine Method

Object: | TextStream
Syntax: | ReadLine ()
Returns: | A single line of the file
Description: | This method reads a single line of the file into an array of text characters starting from the current cursor location. In automation terms, this is a VT_BSTRtype. A line is terminated by a <CR><LF>.


Skip

Skip Method

Object: | TextStream
Syntax: | Skip ([in] numBytes)
Description: | This method moves the file cursor ahead the specified number of bytes.


SkipLine

SkipLine Method

Object: | TextStream
Syntax: | SkipLine ()
Description: | This method moves the file cursor ahead one line. A line is terminated by a <CR><LF>.


Write

Write Method

Object: | TextStream
Syntax: | Write ([in] string)
Description: | This method writes the specified text string to the file at the current file cursor location.


WriteBlankLines

WriteBlankLines Method

Object: | TextStream
Syntax: | WriteBlankLines ([in] numLines)
Description: | This method writes the specified number of blank lines to the file at the current file cursor location.


WriteLine

WriteLine Method

Object: | TextStream
Syntax: | WriteLine ([in, optional] string)
Description: | This method writes the specified text string, followed by a <CR><LF>, to the file at the current file cursor location. If no string is specified, a single blank line is written to the file.


TextStream Properties

AtEndOfLine
AtEndOfStream
Column
Line


AtEndOfFile

AtEndOfFile Property

Object: | TextStream
Syntax: | AtEndOfFile ()
Type: | Boolean
Description: | This property returns True if the file cursor is at the end of the file. It returns False if the cursor is at the beginning or middle of the file.


AtEndOfLine

AtEndOfLine Property

Object: | TextStream
Syntax: | AtEndOfLine ()
Type: | Boolean
Read/Write: | Read Only
Description: | This property returns True if the file cursor is at the end of a line in the current file. It returns False if the cursor is at the beginning or middle of a line.


AtEndOfStream

AtEndOfStream Property

Object: | TextStream
Syntax: | AtEndOfStream ()
Type: | Boolean
Read/Write: | Read Only
Description: | This property returns True if the file cursor is at the end of the file. It returns False, if the cursor is at the beginning or middle of the file.


Column

Column Property

Object: | TextStream
Syntax: | Column ()
Type: | Integer
Read/Write: | Read Only
Description: | This property returns the current column number, numbered from 1-n.


Line

Line Property

Object: | TextStream
Syntax: | Line ()
Type: | Integer
Read/Write: | Read Only
Description: | This property returns the current line number, numbered from 1-n.


The PermItem Object

The PermItem object represents a single trustee's permissions on a single securable object.

PermItem Methods

PermItem Properties


PermItem Methods

RemoveEntry


RemoveEntry

RemoveEntry Method

Object: | PermItem
Syntax: | RemoveEntry ()
Description: | This method removes this entry from the ACL.


PermItem Properties

AccessRights
Delete
Execute
FullControl2
ListContents2
Modify2
NoAccess
Ownership
Permissions
Read
Read2
ReadExecute2
RightsType
Trustee
Write
Write2


AccessRights

AccessRights Property

Object: PermItem
Syntax: AccessRights
Type: Long
Read/Write: Read Only
Description: This property indicates the combined rights of a file or directory.

The SAPermissionsRights can have any of the following values:

Constant | Value | Description
SANoAccess | 1 | All Access is denied.
SARead | 2 | The file can be read.
SAWrite | 4 | The file can be written.
SAExecute | 8 | The file can be executed.
SADelete | 16 | The file can be deleted.
SAPermissions | 32 | Permissions on the file can be changed.
SAOwner | 64 | Allows taking ownership of the file.
SAFull | 126 | Allows all of the above permissions (except NoAccess).
saList (Windows 2000 only) | 256 | Folder content list can be viewed.
saReadExecute (Windows 2000 only) | 512 | The file can be read and executed.
saModify (Windows 2000 only) | 1024 | The file can be modified.


Delete

Delete Property

Object: | PermItem
Syntax: | Delete
Type: | Boolean
Read/Write: | Read Only
Description: | This property indicates that the trustee can delete the file.


Execute

Execute Property

Object: | PermItem
Syntax: | Execute
Type: | Boolean
Read/Write: | Read Only
Description: | This property indicates that execute access is available.


FullControl2

FullControl2 Property

Object: PermItem
Syntax: FullControl2
Type: SAAccessType
Read/Write: Read Only
Description: This property is for use on Windows 2000 systems only. It indicates that the trustee has permissions equivalent to "Full Control" in the Windows 2000 access control property page.

SAAccessType
Constant | Value | Description
SAALLOW | 1 | This privilege is granted.
SADENY | 2 | This privilege is not granted.
SANOTSET | 3 | This privilege is set.


ListContents2

ListContents2 Property

Object: PermItem
Syntax: ListContents2
Type: SAAccessType
Read/Write: Read Only
Description: This property is for use on Windows 2000 systems only. It indicates that the trustee has permissions equivalent to "List Folder" Contents in the Windows 2000 access control property page.

SAAccessType
Constant | Value | Description
SAALLOW | 1 | This privilege is granted.
SADENY | 2 | This privilege is not granted.
SANOTSET | 3 | This privilege is set.


Modify2

Modify2 Property

Object: PermItem
Syntax: Modify2
Type: SAAccessType
Read/Write: Read Only
Description: This property is for use on Windows 2000 systems only. It indicates that the trustee has permissions equivalent to "Modify" in the Windows 2000 access control property page.

SAAccessType
Constant | Value | Description
SAALLOW | 1 | This privilege is granted.
SADENY | 2 | This privilege is not granted.
SANOTSET | 3 | This privilege is set.


NoAccess

NoAccess Property

Object: | PermItem
Syntax: | NoAccess
Type: | Boolean
Read/Write: | Read Only
Description: | This property indicates that no access right is available for this trustee.


Ownership

Ownership Property

Object: | PermItem
Syntax: | Ownership
Type: | Boolean
Read/Write: | Read Only
Description: | This property indicates that the trustee has rights to change the ownership of the file.


Permissions

Permissions Property

Object: | PermItem
Syntax: | Permissions
Type: | Boolean
Read/Write: | Read Only
Description: | This property indicates that the trustee has rights to changes the permissions.


Read

Read Property

Object: | PermItem
Syntax: | Read
Type: | Boolean
Read/Write: | Read Only
Description: | This property indicates that read access is available.


Read2

Read2 Property

Object: PermItem
Syntax: Read2
Type: SAAccessType
Read/Write: Read Only
Description:

This property is for use on Windows 2000 systems only. It indicates that the trustee has permissions equivalent to "Read" in the Windows 2000 access control property page.

SAAccessType
Constant | Value | Description
SAALLOW | 1 | This privilege is granted.
SADENY | 2 | This privilege is not granted.
SANOTSET | 3 | This privilege is set.


ReadExecute2

ReadExecute2 Property

Object: PermItem
Syntax: ReadExecute2
Type:

SAAccessType

SAAccessType
Constant | Value | Description
SAALLOW | 1 | This privilege is granted.
SADENY | 2 | This privilege is not granted.
SANOTSET | 3 | This privilege is set.
Read/Write: Read Only
Description: This property is for use on Windows 2000 systems only. It indicates that the trustee has permissions equivalent to "Read & Execute" in the Windows 2000 access control property page.


RightsType

RightsType Property

Object: PermItem
Syntax: RightsType
Type: Long
Read/Write: Read Only
Description: This property indicates the rights type for either a file or a directory.

The SAPermissionsRightsTypes can have any of the following values:

Constant | Value | Description
SAFileRights | 1 | Permissions apply to files.
SADirRights | 2 | Permissions apply to directories.
SADirFileRights | 3 | Permissions apply to both files and directories.


Trustee

Trustee Property

Object: | PermItem
Syntax: | Trustee
Type: | String
Read/Write: | Read Only
Description: | This property returns the trustee's name in the DOMAIN\USER or DOMAIN\GROUPformat.


Write

Write Property

Object: | PermItem
Syntax: | Write
Type: | Boolean
Read/Write: | Read Only
Description: | This property indicates that write access is available.


Write2

Write2 Property

Object: PermItem
Syntax: Write2
Type: SAAccessType
Read/Write: Read Only
Description:

This property is for use on Windows 2000 systems only. It indicates that the trustee has permissions equivalent to "Write" in the Windows 2000 access control property page.

SAAccessType
Constant | Value | Description
SAALLOW | 1 | This privilege is granted.
SADENY | 2 | This privilege is not granted.
SANOTSET | 3 | This privilege is set.


Key Features

  • Sends e-mail from any COM client
  • Similar object model to ServerObjects' AspMail
  • Written for high performance
  • Supports all threading models
  • Pretty Good Privacy (PGP) is supported in Active Server Pages
  • Supports common functions like file attachments, multiple encoding schemes, and many others
  • Login authentication with the server
  • Mass mail

SMTPmail has one object: the SMTP Mailer.


The SMTP Mailer Object

SMTP Mailer is SMTPmail's principal object.

SMTP Mailer Methods

SMTP Mailer Properties


SMTP Mailer Methods

AddAttachment
AddBCC
AddCC
AddExtraHeader
AddRecipient
ClearAllRecpients
ClearAttachments
ClearBCCs
ClearBodyText
ClearCC
ClearExtraHeaders
ClearRecipients
EncodeHeader
GetBodyTextFromFile
GetHtmlTextFromFile
GetPlainTextFromFile
GetTempPath
MassMail
SendMail


AddAttachment

AddAttachment Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.AddAttachment ([in] <Filename as String>)
Description: | This method adds attachments to current message. Filename indicates the file you are attaching. Filename must be an explicit path.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        method adds attachments to current message. mailer.AddAttachment "c:\file.ext" ...
        %>


AddBCC

AddBCC Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.AddBCC([in] <Name as String>, <E-mail as String>)
Returns: | True/False
Description: | This method adds a recipient to the Blind Carbon Copy (BCC) list.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Add the
        recipient to the BCC: list of the email. '--- You can add as many people as necessary
        mailer.AddBCC "Joe Smith", "joesmith@unknown.com" ... %>


AddCC

AddCC Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.AddCC ([in] <Name as String>, <E-mail as String>)
Returns: | True/False
Description: | This method adds a new recipient to the CC: list of a message. It returns True if the address is syntactically valid, False if it is not.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Add the
        recipient to the CC: list of the email. '--- You can add as many people as necessary
        mailer.AddCC "Joe Smith", "joesmith@unknown.com" ... %>


AddExtraHeader

AddExtraHeader Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.AddExtraHeader ([in] <X-Header as String>)
Returns: | True/False
Description: | This method adds extra X-Headers to the message's mail envelope. The X-Header value is a string that represents a proper SMTP X-Header. This method returns True is the X-Header is added, False if it is not.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        method adds extra X-Headers to the message's mail envelope mailer.AddExtraHeader
        "x-mycompany: specialinstruction" ... %>


AddRecipient

AddRecipient Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.AddRecipient ([in] <Name as String>, <E-mail as String>)
Returns: | True/False
Description: | This method adds another recipient to the To: list of the message. It returns True if the recipient is a valid address, False if it is not.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Add the
        recipient who will receive the email. '--- You can add as many people as necessary
        mailer.AddRecipient "Joe Smith", "joesmith@unknown.com" ... %>


ClearAllRecipients

ClearAllRecipients Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.ClearAllRecipients ()
Description: | This method clears all recipients from all lists (To:, CC:, and BCC:).

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Remove
        all recipients from e-mail '--- includes TO, CC and BCC recipients. mailer.ClearAllRecipients
        ...


ClearAttachments

ClearAttachments Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.ClearAttachments ()
Description: | This method removes any attachments to the current message.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Remove
        all attachments from e-mail mailer.ClearAttachments ... %>


ClearBCCs

ClearBCCs Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.ClearBCCs ()
Description: | This method removes any recipients from the Blind Carbon Copy (BCC) list.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Remove
        all BCC recipients from e-mail mailer.ClearBCCs ... %>


ClearBodyText

ClearBodyText Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.ClearBodyText ()
Description: | This method removes any body text assigned to the message that may have been set by the BodyText property.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Remove
        body text from e-mail mailer.ClearBodyText ... %>


ClearCC

ClearCCs Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.ClearCCs ()
Description: | This method removes any recipients from the message's CC: list.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Remove
        all CC recipients from e-mail mailer.ClearCCs ... %>


ClearExtraHeaders

ClearExtraHeaders Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.ClearExtraHeaders ()
Description: | This method removes any X-Headers that were set by the AddExtraHeader method .

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Remove
        X-Headers from e-mail mailer.ClearExtraHeaders ... %>


ClearRecipients

ClearRecipients Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.ClearRecipients ()
Description: | This method removes any recipients currently in a message's To: list.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Remove
        all TO recipients from e-mail mailer.ClearRecipients ... %>


EncodeHeader

EncodeHeader Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.EncodeHeader ([in] <value>)
Returns: | String
Description: | This method encodes a string in RFC1522 format to provide support for 8-bit mail headers. The encoded strValue is returned as a string.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- The Encodeheader
        method encodes a string in RFC1522 format to provide support for 8-bit mail headers.
        mailer.Subject = mailer.EncodeHeader("££££££££££££") ... %>


GetBodyText

GetBodyTextFromFile Method

Object: SMTP Mailer
Syntax:
<OBJECT>.GetBodyTextFromFile ([in] Filename as String, [EraseFile as Boolean],
            [ShowWindow as Boolean])
Description:

GetBodyTextFromFile loads a mail message's body text from a file. Optionally, GetBodyTextFromFile can invoke PGP to encryt the file content.

To invoke the PGP executable:

  1. Set the PGPPath property.
  2. Set the PGPParams property.
  3. Assign a value to GetBodyTextFromFile's EraseFile parameter. Set the parameter to True to erase the file after its content is loaded.
  4. Assign a value to GetBodyTextFromFile's ShowWindow parameter. When ShowWindow is set to True, the PGP process window will open. This is useful for debugging. ShowWindow should be set to False in a production environment.
Note: The two optional parameters EraseFile and ShowWindow work only in a PGP context. You cannot use EraseFile to delete a file if you do not invoke the PGP executable. When GetBodyTextFromFile is used without PGP, it is equivalent to GetPlainTextFromFile.

Example:
<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set the
            path of the PGP executable mailer.PGPPath = "E:\Program Files\Network Associates\PGPcmdln\PGP.exe"
            ... '--- Set the parameters PGP will use to encrypt the file. The '--- following
            signs msg.txt with someone@host.com's private key. mailer.PGPParams = "-s -a ""c:\email\msg.txt""
            -u _ ""<someone@host.com>"" -z ""passwordkey""" ... '--- Invoke the PGP executable
            to encrypt the file, load the '--- file into the email's body text, and erase the
            file after '--- its content is loaded. Do not open the PGP executable '--- window.
            mailer.GetBodyTextFromFile "c:\email\msg.asc", True, False ... %>


GetHtmlTextFromFile

GetHtmlTextFromFile Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.GetHtmlTextFromFile ([in] <Filename as String>)
Description: | This method loads the message's HTML-formatted body text from a file. GetHtmlTextFromFile takes HTML-formatted text from any type of text file, including (but not limited to) .doc, .htm and .txt. Please refer to the documentation for the CharSetand CustomCharSet properties if the text in the file does not use the standard US English character set.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- '---
        Load HTML-formatted body text into e-mail from file. mailer.GetHtmlTextFromFile
        "c:\email\bodytext.htm" ... %>


GetPlainTextFromFile

GetPlainTextFromFile Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.GetPlainTextFromFile ([in] <Filename as String>)
Description: | This method loads the message's Plain-formatted body text from a file. GetPlainTextFromFile takes Plain-formatted text from any type of text file, including (but not limited to) .doc, .htm and .txt. Please refer to the documentation for the CharSetand CustomCharSet properties if the text in the file does not use the standard US English character set.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- '---
        Load Plain-formatted body text into e-mail from file. mailer.GetPlainTextFromFile
        "c:\email\bodytext.txt" ... %>


GetTempPath

GetTempPath Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.GetTempPath()
Returns: | String
Description: | This method returns the path for temporary mail files set by the operating system.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        method returns the path for temporary mail files set by the operating system Response.Write
        "<BR> " & mailer.GetTempPath ... %>


MassMail Method

Object: SMTP Mailer
Syntax: <OBJECT>.MassMail ([in] RecordSet Pointer)
Returns: True/False
Description: The MassMail method works like a mail merge to send e-mail messages to a mailing list with only one connection to the mail server.

MassMail replaces the SendMail method. You should not use the SendMail method if you are using the MassMail method.

MassMail sends each e-mail as it replaces the coded template with values from your data source. When creating the template in your code, use "%%" delimiter characters on each side of the column names in order to indicate which columns you would like SMTPMail to pull data from when using the MassMail feature.

For example, if you want to pull an e-mail address out of a column named "EmailAddress", you would refer to it in your code as %%EmailAddress%%. If you want to use the delimiter characters, "%%", in the subject or body of your e-mail without referring to a data source column, you should put the escape character ("\") in front of them, like this: "\%\%".

The MassMail method does not handle bounced messages.

This functionality is compatible with LSMTP.

Note: You can use the MassMail functionality from within an HTML message or when getting the body text of a message from an HTML file, but SMTPMail will read the column name value inside delimiters literally, so you cannot use HTML formatting or any additional characters inside the delimiters. For example, if you use %%<B>E</B>mailAddress%%as the value inside the delimiters, SMTPMail will read the column name as"<B>E</B>mailAddress", will not recognize it as a valid column name and will pass it out to the body text of the e-mail as HTML-formatted text, " %%EmailAddress%% ".

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- '---
        Set the Subject, Recipient and BodyText of the mass e-mail mailer.Subject = "Regarding
        Order Number %%OrderNumber%%" mailer.BodyText = "Dear %%FirstName%% :" & vbCrLf
        ... mailer.AddRecipient "%%FirstName%% %%LastName%%", "%%EmailAddress%%" mailer.AddCC
        "Mail Administrator", "webmaster@website.com" '--- '--- Set remote host name mailer.RemoteHost
        = "servername" '--- '--- Set database connection filePath = Server.MapPath("massmail.mdb")
        strConnect = "DBQ=" & filePath & ";Driver={Microsoft Access Driver (*.mdb)};DriverId=25;FIL=MSAccess;"
        '--- Dim objRec Dim objCommand '--- Set objCommand = Server.CreateObject ("ADODB.Command")
        Set objRec = Server.CreateObject("ADODB.Recordset") '--- objCommand.ActiveConnection
        = strConnect objCommand.CommandType = adcmdText objCommand.CommandText = "SELECT
        LastName, EmailAddress, FirstName, OrderNumber FROM Customers" Set objRec = objCommand.Execute
        '--- '--- Until end of recordset is reached, send e-mail If mailer.MassMail (objRec)
        Then Response.Write "Mail sent..." Else Response.Write "Mail failure." End If '---
        Set objRec = nothing Set mailer = nothing ... %>


SendMail

SendMail Method

Object: | SMTP Mailer
Syntax: | <OBJECT>.SendMail()
Returns: | True/False
Description: | This method attempts to send the e-mail message.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Sends
        the message and can be used to verify if there if it has been sent. If mailer.SendMail
        Then Response.Write "<P>Mail sent..." Else Response.Write "<P>Mail failure.
        Check mail host server name and tcp/ip connection..." End If ... %>


UseMSPickUpDir

UseMSPickUpDir Method *

Object: SMTP Mailer
Syntax: <OBJECT>.UseMSPickUpDir ([in] Directory as String)
Description: For each configured domain, Microsoft SMTP Service (Service) supports the placement of all incoming messages directly into a Drop folder. This allows the Service to be used as an e-mail receiver for other applications.

In additon to connecting to a TCP port to send messages, applications can also use a Pickup folder. Once a message is placed in the Pickup folder, the Service delivers the message.

The UseMSPickUpDir method allows you to use the Service and to specify the path of the pickup directory.

If the directory specified is the Microsoft Pickup directory, the Service will pick the messages up from the directory. If it is not the Pickup directory, the messages will only be stored in the directory, but will not be picked up by the Service. Check the Microsoft SMTP Service documentation for instructions on configuring this service.

Important: This will only work if Microsoft SMTP Service is configured and running correctly.

The RemoteHost property is NOT needed when using the UseMSPickUpDir method.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... mailer.UseMSPickUpDir
        ("c:\pickup") ... %>
* ONLY available in the Full version of SoftArtisans SMTPmail.


prog_ref_smtp_properties

BodyText
CharSet
CodePage
ConfirmRead
ContentTransferEncoding
ContentType
CustomCharSet
DateTime
Encoding
Expires
FromAddress
FromName
HtmlText
IgnoreMalformedAddress
IgnoreRecipientErrors
Live
LoggingLevel
MailFromAddress
MassMailFailed
MassMailTotal
Organization
Password
PGPParams
PGPPath
Priority
RemoteHost
ReplyTo
Response
ReturnPath
ReturnReceipt
SMTPLog
Subject
SuppressMsgBody
TimeOut
Urgent
UseMSMailHeaders
UserName
Version
WordWrap
WordWrapLen


BodyText

BodyText Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.BodyText = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property contains the body text of a message.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set the
        body text of the e-mail message. mailer.BodyText = "Put your message here" &
        vbCRLF ... %>


CharSet

CharSet Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.CharSet = <value>
Type: | Integer
Read/Write: | Read/Write
Description: | This property indicates the character set. It returns 1 if the character set is US-ASCII (default), or 2 if the character set is ISO-8859-1.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property sets the character set. '--- 1 = US-ASCII '--- 2 = ISO-8859-1 mailer.CharSet
        = 2 ... %>


CodePage

CodePage Property

Object: SMTP Mailer
Syntax: <OBJECT>.CodePage [=Language Code as Long]
Type: Long
Read/Write: Read/Write
Description:

Set CodePage if an email's BodyText and/or HTMLText contains Unicode values (such as, non-English characters). The value of Codepage will be use to convert Unicode values to CharSet bytes. Use this property in conjunction with CustomCharSet.

For a complete list of Codepage values, see Microsoft's Character Set Recognition Reference.

* The CodePage property is not available in SMTPMailFree.

Example:
<% Set Mailer = Server.CreateObject("SoftArtisans.SMTPMail") '--- CodePage
            for Arabic (Windows) Mailer.CodePage = 1256 '--- CharSet for Arabic (Windows) Mailer.CustomCharSet
            = windows-1256 ... %>


ConfirmRead

ConfirmRead Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.ConfirmRead = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property sets a confirmation read flag. It only works if the recipient's e-mail program supports confirmation. If set to True, the recipient's e-mail program sends a notice confirming that the e-mail has been read.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property only works if the recipient's e-mail program supports confirmation. mailer.ConfirmRead
        = true ... %>


ContentType

ContentType Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.ContentType = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property lets you set the ContentType header of a message's BodyText. This property is ignored if the message contains file attachments.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set the
        ContentType header of a message's BodyText. mailer.ContentType = "text/html" ...
        %>


ContentTransferEncoding

ContentTransferEncoding Property

Object: SMTP Mailer
Syntax: <OBJECT>.ContentTransferEncoding = <value>
Type: Integer
Read/Write: Read/Write
Description: The ContentTransferEncoding property allows you to set standard contents encoding. The default value for this property is 7-bit.

Many Content-Types which could usefully be transported via email are represented, in their "natural" format, as 8-bit character or binary data. Such data cannot be transmitted over some transport protocols. For example, RFC 821 restricts mail messages to 7-bit US-ASCII data with lines no longer than 1000 characters.

It is necessary, therefore, to define a standard mechanism for re- encoding such data into a 7-bit short-line format. Such encodings are indicated by the "Content-Transfer-Encoding" header field. The Content-Transfer-Encoding field is used to indicate the type of transformation that has been used in order to represent the body in an acceptable manner for transport.

Note: SMTPmail's ContentTransferEncoding property should be set after setting the CharSet property or the CustomCharSet property. By default, CharSet is US-ASCII, ContentTransferEncoding is 7bit. All other settings (of CharSet and CustomCharSet) are quote-printable, so put the ContentTransferEncoding customization after setting these properties.

This feature is based on the "MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies" protocol in RFC1521.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set CharSet
        to ISO=9959-1 '------------------------------------ '--- 1 = US ASCII '--- 2 = ISO-9959-1
        '------------------------------------ mailer.charset = 2 '--- '--- Set the CustomCharSet
        to Polish (ISO-8859-2) mailer.CustomCharSet = "ISO-8859-2" '--- '--- Set ContentTransferEncoding
        to 8bit '------------------------------------ '--- 1 = 7bit '--- 2 = quote-printable
        '--- 3 = base64 '--- 4 = 8bit '------------------------------------ mailer.ContentTransferEncoding
        = 4 ... %>


CustomCharSet

CustomCharSet Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.CustomCharSet = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property lets you use a character set other than the types you can set using the CharSet property. For a complete list of CustomCharSet values, see Microsoft's Character Set Recognition Reference . See also, CodePage.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set if
        you use a character set other than US-ASCII or ISO-8859-1. '--- "Big5" is the Chinese
        Traditional character set mailer.CustomCharSet = "big5" ... %>


DateTime

DateTime Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.DateTime = <value>
Type: | Date/Time String
Read/Write: | Read/Write
Description: | This property lets you override the default date/time header created by SMTPmail. You must provide a valid date/time string.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Used
        to override the default date/time header mailer.DateTime = "Wed, 01 August 2001
        10:53:49 -0500" ... %>


Encoding

Encoding Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.Encoding = <value>
Type: | Integer
Read/Write: | Read/Write
Description: | This property indicates the encoding type for any attachments. Value can be 1 for UUEncoded or 2 for MIME. The default is MIME.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Sets
        encoding type for any attachments. '--- Value can be 1 for UUEncoded or 2 for MIME
        (default). mailer.Encoding = 1 ... %>


Expires

Expires Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.Expires
Type: | Date
Read/Write: | Read Only
Description: | This property returns the date that an eval version component stops functioning. This property is only valid if the component is an eval version. Since SoftArtisans SMTPmailFREE is a free component, there will never be an expiring date.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Get and
        print the internal expiration date of SMTPMail Response.Write "This evaluation of
        SoftArtisans SMTPMail expires on: " & Mailer.Expires ... %>


FromAddress

FromAddress Property

Object: SMTP Mailer
Syntax: SMTPMailer.FromAddress = email address
Type: String
Read/Write: Read/Write
Description:

FromAddress specifies the e-mail address from which the message was generated. FromAddress is a required field.

If you do not set MailFromAddress, the value of FromAddress will be assigned both to the MAIL FROM field and to subsequent headers.

The value of the optional property MailFromAddress will only be used in the MAIL FROM field. The value of FromAddress will always be used in subsequent headers.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set Properties
        for The name of the sender (FromName) and their email address (FromAddress) Mailer.FromName
        = "Joe Smith" Mailer.FromAddress = "JSmith@unknown.com" ... %>


FromName

FromName Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.FromName = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property indicates the name of the person who generated the message.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set Properties
        for The name of the sender (FromName) and their email address (FromAddress) Mailer.FromName
        = "Joe Smith" Mailer.FromAddress = "JSmith@unknown.com" ... %>


HtmlText

HtmlText Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.HtmlText = <value>
Type: | String
Read/Write: | Read/Write
Description: | The HtmlText property can be used instead of or in addition to the BodyText property to pass HTML-formatted text into the body of an e-mail.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- '---
        Set the HTML text that will be passed into the body of the e-mail. mailer.HTMLText
        ="Regarding <B> Order Number: </B> <I> 245 </I>" ... %>


IgnoreMalformedAddress

IgnoreMalformedAddress Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.IgnoreMalformedAddress = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property indicates whether SMTPmail will check for an @ sign in the email addresses used in the AddRecipient, AddCC, and AddBCC methods. Any errors are returned in the Response property. By default, this property is set to False. When sent to True, SMTPmail does not validate address syntax.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Turn
        IgnoreMalformedAddress property ON '--- SMTPmail will not validate address syntax.
        mailer.IgnoreMalformedAddress = True ... %>


IgnoreRecipientErrors

IgnoreRecipientErrors Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.IgnoreRecipientErrors = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property indicates whether SoftArtisans SMTPmail will ignore error messages from the SMTP server generated by invalid addresses. Default is True.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Turn
        IgnoreRecipientErrors OFF. '--- SMTPmail will return errors generated by invalid
        addresses. mailer.IgnoreRecipientErrors = False ... %>


Live

Live Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.Live = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property lets you test that SoftArtisans SMTPmail works, without actually having an SMTP server. By default, this property is set to True, in which case messages are sent to the recipients. If you set Live to False, only a NET SEND (alert) message will be sent to the specified user. No e-mail will be sent. The message receiver will be determined by the FromName property and the message will only contain the result of the Subject property; the message body will not be sent. This is useful for testing without an SMTP server.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property lets you test that SoftArtisans SMTPMail works, without '--- actually having
        an SMTP server. mailer.Live = false ... %>


LoggingLevel

LoggingLevel Property *

*This property is not available in SMTPMailFree.

Object: SMTP Mailer
Syntax: <OBJECT>.LoggingLevel = <value>
Type: Long
Read/Write: Read/Write
Description: LoggingLevel is available in SMTPMail 2.3 and later versions. LoggingLevel works only on Windows NT and Windows 2000.

Use LoggingLevel in conjunction with the SMTPLogproperty. SMTPLog sets the location of a log file that records information about sent messages. LoggingLevel sets the type of log file that SMTPMail will create.

When LoggingLevel is set to 1 or 2 a new log file is created per day, by default. This log creation interval value is set by the registry key NewLogFileInterval. The value of NewLogFileInterval is a number of days (default value: 1). To change the value of this key:
  1. From the Start menu, select Run.
  2. Enter regedit and click Ok.
  3. Open HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\SMTPMail\Parameters.
  4. Right-click NewLogFileInterval and select Modify.
  5. In the Value Data field enter a number of days.

LoggingLevel Values
0

(Default value) 		Backward compatible with the SMTPLog property in versions earlier than 2.3. Level 0 logs detailed debug information. The log file is not cumulative; it records information about a single sent message.
1 Cumulative history of messages sent. For each sent message, level 1 logs:
  • Start_Date_Time
  • Remote_Host
  • From
  • To
  • SMTP_Status
  • Overall_Status
  • End_Date_Time
Note: A cumulative log file may contain both level 1 and level 2 records.
2 Cumulative history of messages sent. Contains complete message data. For each sent message, level 2 logs:
  • Start_Date_Time
  • Remote_Host
  • From
  • To
  • SMTP_Status
  • Message_Data
  • Overall_Status
  • End_Date_Time
Note: A cumulative log file may contain both level 1 and level 2 records.
SMTP_Status:

SMTP_Status codes include:

211 | System status, or system help reply | 500 | Syntax error, command unrecognized (This may include errors such as command line too long)
214 | Help message (Information on how to use the receiver or the meaning of a particular non-standard command) | 501 | Syntax error in parameters or arguments
220 | Service ready | 502 | Command not implemented
221 | Service closing connection | 503 | Bad sequence of commands
250 | Requested mail action okay, completed | 504 | Command parameter not implemented
251 | User not local; will forward to | 550 | Requested action not taken: mailbox unavailable (E.g., mailbox not found, no access)
354 | Start mail input | 551 | User not local; please try
421 | Service not available, closing transmission channel | 552 | Requested mail action aborted: exceeded storage allocation
450 | Requested mail action not taken: mailbox unavailable (E.g., mailbox busy) | 553 | Requested action not taken: mailbox name not allowed (E.g., mailbox syntax incorrect)
451 | Requested action aborted: local error in processing | 554 | Transaction failed
452 | Requested action not taken: insufficient system storage
Message_Data:

The Message_Data field contains the data that SMTP mail servers send and receive, for example:

From: john@yahoo.com To: <anne@hotmail.com> Subject: <Hi>
            Date: Wed, 19 Feb 2003 14:00:49 +0200 Content-Type: text/plain; charset="US-ASCII"
            Content-Transfer-Encoding: 7bit Hi John
Examples:
Set Mailer = Server.CreateObject("SoftArtisans.SMTPMail") Mailer.LoggingLevel
            = 0 '--- When LoggingLevel is set to 0, set SMTPLog '--- to the log file's path
            and include the complete '--- file name. The file is replaced with each '--- request.
            Mailer.SMTPLog = "C:\Mail\Log\Msg1.log"
Set Mailer = Server.CreateObject("SoftArtisans.SMTPMail") Mailer.LoggingLevel
            = 1 '--- When LoggingLevel is set to 1, set SMTPLog '--- to the log file's path
            and file name prefix. '--- The log generated will be cumulative and the '--- log
            file's name will contain the date. The '--- format of the file name generated by
            this '--- example would be "Log_YYYYMMDD.log". Mailer.SMTPLog = "C:\Mail\Log"
Set Mailer = Server.CreateObject("SoftArtisans.SMTPMail") Mailer.LoggingLevel
            = 2 '--- When LoggingLevel is set to 2, set SMTPLog '--- to the log file's path
            and file name prefix. '--- The log generated will be cumulative and the '--- log
            file's name will contain the date. The '--- format of the file name generated by
            this '--- example would be "Log_YYYYMMDD.log". Mailer.SMTPLog = "C:\Mail\Log"


MailFromAddress

MailFromAddress Property

Object: SMTP Mailer
Syntax: SMTPMailer.MailFromAddress = email address
Type: String
Read/Write: Read/Write
Description:

MailFromAddress specifies the e-mail address from which the message was sent. The value of MailFromAddress will be used in the message's MAIL FROM field. The value of MailFromAddress will not be used in subsequent headers.

MailFromAddress is not a required property. If you do not set MailFromAddress, the value of FromAddress will be assigned both to the MAIL FROM field and to subsequent headers. Note that you must set the FromAddress property.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... Mailer.FromName
        = "Joe Smith" Mailer.MailFromAddress = "JSmith@unknown.com" Mailer.FromAddress =
        "JohnS@unknown.org" ... %>


MassMailFailed

MassMailFailed Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.MassMailFailed
Type: | Double
Read/Write: | Read Only
Description: | This property returns the number of e-mails that failed while MassMail was running. The MassMailFailed property is only useful if you are using the MassMail method. If you are not using the MassMail method, this property will return 0. The MassMailFailed property can be used in conjunction with the MassMailTotal property to find the number of successfully sent e-mails in a mass mailing. MassMailTotal Property - MassMailFailed Property = successfully sent e-mails

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Print
        the number of failed e-mails in the current SMTPMail MassMail Response.Write "The
        number of e-mails that failed during MassMail is: " & Mailer.MassMailFailed
        ... %>


MassMailTotal

MassMailTotal Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.MassMailTotal
Type: | Double
Read/Write: | Read Only
Description: | This property returns the total number of e-mails that were attempted while MassMail was running. The MassMailTotal property is only useful if you are using the MassMail method. If you are not using the MassMail method, this property will return 0. The MassMailTotal property can be used in conjunction with the MassMailFailed property to find the number of successfully sent e-mails in a mass mailing. MassMailTotal Property - MassMailFailed Property = successfully sent e-mails

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Print
        the total number of attempted e-mails in the current SMTPMail MassMail Response.Write
        "The number of e-mails that were attempted during MassMail is: " & Mailer.MassMailTotal
        ... %>


Organization

Organization Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.Organization = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property sets the Organization header in a message.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Sets
        the Organization header. mailer.Organization = "SoftArtisans SMTP Org" ... %>


Password

Password Property *

Object: | SMTP Mailer
Syntax: | <OBJECT>.Password = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property allows you to set the password which you can use to authenticate with the mail server. This property can be used to prevent spam from being sent from your mail server. It must be used in conjunction with the UserName property . If you do not set BOTH the UserName and Password properties, your mail will not be authenticated with the server. Only Login Authentication is supported at this time. This feature is based on the "SMTP Service Extension for Authentication" protocol in RFC2554.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- '---
        Set the UserName and Password with which mail server will authenticate mailer.UserName
        ="User name" mailer.Password ="Password" '--- '--- If mail server authenticates,
        send e-mail mailer.SendMail ... %>
* ONLY available in the Full version of SoftArtisans SMTPmail.


PGPParams

PGPParams Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.PGPParams = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property contains the parameters that PGP uses to process the message. This string contains parameters that are passed to the PGP command line. This property must be used in conjunction with the PGPPath property. For more information on PGP and the different parameters that it requires, visit www.pgp.com. See also, GetBodyTextFromFile.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set the
        path of the PGP executable mailer.PGPPath = "E:\Program Files\Network Associates\PGPcmdln\PGP.exe"
        '--- '--- Set the parameters with which PGP will function '--- These parameters
        are dependant on the executable set in the PGPPath property '--- In this example,
        we want PGP to encrypt a plaintext file with recipient's public key mailer.PGPParams
        = "-s -a ""c:\test1.txt"" -u ""<Anyone@unknown.com>"" -z ""passwordkey"""
        ... %>


PGPPath

PGPPath Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.PGPPath = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property returns the path for the location of the PGP executable. It should be used in conjunction with the PGPParams property to set PGP security on the e-mail. See also, GetBodyTextFromFile.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set the
        path of the PGP executable mailer.PGPPath = "E:\Program Files\Network Associates\PGPcmdln\PGP.exe"
        '--- '--- Set the parameters with which PGP will function '--- These parameters
        are dependant on the executable set in the PGPPath property '--- In this example,
        we want PGP to encrypt a plaintext file with recipient's public key mailer.PGPParams
        = "-s -a ""c:\test1.txt"" -u ""<Anyone@unknown.com>"" -z ""passwordkey"""
        ... %>


Port

Port Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.Port = <value>
Type: | Long
Read/Write: | Read/Write
Description: | Sets or returns the SMTP port number. Port is set to 25 by default.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set the
        port that SMTPmail should use to send e-mail. mailer.Port = 1025 ... %>


Priority

Priority Property

Object: SMTP Mailer
Syntax: <OBJECT>.Priority = <value>
Type: Integer
Read/Write: Read/Write
Description: This property sets the priority level for a message. Priority levels are one through five and are reflected in the X-Priority.

Valid values are:

Value | Description
1 | High
3 | Normal
5 | Low

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '------------------------------------
        '--- Set priority and if message is urgent. Prioritys are 1, 3, 5 and '--- are reflected
        in the X-Priority header '--- 1 = High, 3 = Normal, 5 = Low '------------------------------------
        mailer.Priority = 1 ... %>


RemoteHost

RemoteHost Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.RemoteHost = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property indicates the remote SMTP host through which the message is sent. The value passed to this property can be an IP address or mail server name.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Set the
        Remote Host (SMTP) that SMTPMail will use to send mail. '--- You can set a condition
        to verify that Remote Host is correct. strMailHost = "MailServer" If strMailHost
        = "mailhost.xyz.com" Then Response.Write "<h2 align=center>Error: You need
        to change the mailhost to your SMTP server address</h2>" Else mailer.RemoteHost
        = strMailHost End If ... %>


ReplyTo

ReplyTo Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.ReplyTo
Type: | String
Read/Write: | Read/Write
Description: | This property lets you specify a different e-mail address to which replies will be sent.


ReturnPath

ReturnPath Property

Object: SMTP Mailer
Syntax: SMTPMailer.ReturnPath = <email address>
Type: String
Read/Write: Read/Write
Description:

ReturnPath sets a message's return-path header. ReturnPath is not a required property. If you do not set ReturnPath, the value of FromAddresswill be used in the return-path header field.

Note that you must include <> in the ReturnPath value, as follows:

Mailer.ReturnPath = "<info@softartisans.com>"


Response

Response Property

Object: SMTP Mailer
Syntax: <OBJECT>.Response
Type: String
Read/Write: Read Only
Description: This property returns any of the following types of error messages:.

  • SMTP error messages, such as SMTP server response error.
  • System error messages, such as temporary file creation failure error.
  • Error messages that help the user to find problems beyond the SMTP returned message, such as MalformedEmailAddress, connection setup, or connection closing.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property returns any errors. Response.Write "<BR> " & mailer.Response
        ... %>


ReturnReceipt

ReturnReceipt Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.ReturnReceipt = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property sets a ReturnReceipt flag. It only works if the recipient's SMTP server supports confirmation and that capability is enabled on the recipient's server. If set to True, the recipient's SMTP server sends a notice confirming that the e-mail has been delivered.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Recipient's
        SMTP server sends a notice confirming that the e-mail has been delivered. '--- This
        property works only if user's server supports notifcation. mailer.ReturnReceipt
        = true ... %>


SMTPLog

SMTPLog Property

Object: SMTP Mailer
Syntax: <OBJECT>.SMTPLog = <value>
Type: String
Read/Write: Read/Write
Description: SMTPLog sets the name and location of a log file that records information about sent messages. SMTPMail will create one of three types of log file, depending on the value of LoggingLevel.

If LoggingLevel = 0

(default value) 		Set SMTPLog to the log file's path and include the complete file name. The file is replaced with each request. For example,
Mailer.SMTPLog = "C:\Mail\Log\Msg1.log"
If LoggingLevel = 1

(Not available in SMTPMailFree) 		Set SMTPLog to the log file's path and file name prefix. The Log generated will be cumulative and the name will contain the date. For example,
Mailer.SMTPLog = "C:\Mail\Log"
The format of the log file generated will be "Log_YYYYMMDD.log".
If LoggingLevel = 2

(Not available in SMTPMailFree) 		Set SMTPLog to the log file's path and file name prefix. The Log generated will be cumulative and the name will contain the date. For example,
Mailer.SMTPLog = "C:\Mail\Log"
The format of the log file generated will be "Log_YYYYMMDD.log".
Examples:
Set Mailer = Server.CreateObject("SoftArtisans.SMTPMail") Mailer.LoggingLevel
            = 0 '--- When LoggingLevel is set to 0, set SMTPLog '--- to the log file's path
            and include the complete '--- file name. The file is replaced with each '--- request.
            Mailer.SMTPLog = "C:\Mail\Log\Msg1.log"
Set Mailer = Server.CreateObject("SoftArtisans.SMTPMail") Mailer.LoggingLevel
            = 1 '--- When LoggingLevel is set to 1, set SMTPLog '--- to the log file's path
            and file name prefix. '--- The log generated will be cumulative and the '--- log
            file's name will contain the date. The '--- format of the file name generated by
            this '--- example would be "Log_YYYYMMDD.log". Mailer.SMTPLog = "C:\Mail\Log"
Set Mailer = Server.CreateObject("SoftArtisans.SMTPMail") Mailer.LoggingLevel
            = 2 '--- When LoggingLevel is set to 2, set SMTPLog '--- to the log file's path
            and file name prefix. '--- The log generated will be cumulative and the '--- log
            file's name will contain the date. The '--- format of the file name generated by
            this '--- example would be "Log_YYYYMMDD.log". Mailer.SMTPLog = "C:\Mail\Log"


Subject

Subject Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.Subject = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property contains the Subject line for the message.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Sets
        Subject line for the message mailer.Subject = "Put your subject here" ... %>


SuppressMsgBody

SuppressMsgBody Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.SuppressMsgBody = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property works in conjunction with the SMTPLog property to indicate whether the log file receives a copy of the message text. When SMTPLog is set to a file and this property is set to True (the default), a copy of the message text is sent to the log file.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Used
        for Logging Debugging log mailer.SMTPLog = "c:\mysmtplog.txt" '--- '--- This property
        works in conjunction with the SMTPLog property to '--- indicate whether the log
        file receives a copy of the message text mailer.SuppressMsgBody = false ... %>


TimeOut

TimeOut Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.TimeOut = <value>
Type: | Integer
Read/Write: | Read/Write
Description: | This property indicates the maximum amount of time, in seconds, that SoftArtisans SMTPMailwaits for a response from the remote. The default is 30 seconds.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property indicates the maximum amount of time, in seconds, '--- that SoftArtisans
        SmtpMail waits for a response from the remote SMTP server mailer.TimeOut = 120 ...
        %>


Urgent

Urgent Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.Urgent = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property sets a flag in the outgoing message that indicates the message is urgent. Not all mail readers support this flag.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property sets a flag in the outgoing message that indicates '--- the message is
        urgent mailer.Urgent = true ... %>


UseMSMailHeaders

UseMSMailHeaders Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.UseMSMailHeaders = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property indicates whether MS-Mail priority headers are sent in addition to the standard SMTP priority headers. By default, MS-Mail priority headers are on. You can turn off the MS-Mail headers by setting this property to False.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property indicates whether Microsoft mail headers will be turned on or off mailer.UseMSMailHeaders
        = false ... %>


UserName

UserName Property *

Object: | SMTP Mailer
Syntax: | <OBJECT>.UserName = <value>
Type: | String
Read/Write: | Read/Write
Description: | This property allows you to set the username which you can use to authenticate with the mail server. This property can be used to prevent spam from being sent from your mail server. It must be used in conjunction with the Password property . If you do not set BOTH the UserName and Password properties, your mail will not be authenticated with the server. Only Login Authentication is supported at this time. This feature is based on the "SMTP Service Extension for Authentication" protocol in RFC2554.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- '---
        Set the UserName and Password with which mail server will authenticate mailer.UserName
        ="User name" mailer.Password ="Password" '--- '--- If mail server authenticates,
        send e-mail mailer.SendMail ... %>
* ONLY available in the Full version of SoftArtisans SMTPmail.


Version

Version Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.Version
Type: | String
Read/Write: | Read Only
Description: | This property returns the version number of the internal component.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- Get and
        print the internal version number of SMTPMail Response.Write "SoftArtisans SMTPMail
        Version: " & Mailer.Version ... %>


WordWrap

WordWrap Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.WordWrap = <value>
Type: | Boolean
Read/Write: | Read/Write
Description: | This property indicates whether the message will word wrap. By default, word wrap is turned off. Set this property to True to turn word wrap on.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property indicates whether the message will word wrap. mailer.WordWrap = true ...
        %>


WordWrapLen

WordWrapLen Property

Object: | SMTP Mailer
Syntax: | <OBJECT>.WordWrapLen = <value>
Type: | Integer
Read/Write: | Read/Write
Description: | This property sets the position at which the message body wraps if the WordWrap property is set.

Example:

<% Set mailer = Server.CreateObject("SoftArtisans.SMTPMail") ... '--- This
        property indicates whether the message will word wrap. mailer.WordWrap = true '---
        '--- This property sets the position at which the message body wraps '--- if the
        WordWrap property is set mailer.WordWrapLen = 50 ... %>


Samples

FileUp includes numerous ASP and ASP.NET sample applications that show you how to use FileUp. The ASP samples are in VBScript. There are VB.NET and C# versions of all ASP.NET samples.

The automatic installation creates the virtual directory SAFileUpSamplesin IIS. To run the samples and view the code, open a browser window, and enter the URL http://localhost/safileupsamples.


Setting Up the Database Samples

Setup Instructions

Note: We highly recommend using Microsoft MDAC 2.0 or later if you intend to perform significant database BLOB (Binary Large OBject - i.e. a file) manipulations. MDAC is available free from http://www.microsoft.com/data. MDAC encompasses all previous Microsoft data components such as ADO, OLE-DB, and the latest ODBC drivers. In our experience it is much reliable for BLOB manipulations than earlier versions of ADO.

Database "Upload.mdb" and "Upload.SQL" Samples - *Located on root of samples
Upload to Database: (Simple, Intermediate, Filename ) , Download From Server: (Simpledatabase), and
File Manager Importing/Exporting Database Blobs: (Import,Export)

We supply a sample Access Database as well as SQL Server Scripts that will create tables that you can use for file uploading.

Setup Instructions for Access:

  1. Find the UPLOAD.MDB file contained in the same directory as this file.
  2. Using the Control Panel, Open the ODBC Data Source Administrator
  3. Click on the "System DSN" tab.
  4. Select "Add..."
  5. Select "Microsoft Access Driver (*.MDB)"
  6. Click on "Finish"
  7. Enter a Data Source name of "AccessUpload"
  8. Click on "Select..." and navigate to the location of the UPLOAD.MDB file.
  9. Click on "OK" and your database is ready to use.

Setup Instructions for SQL-Server:

  1. Find the UPLOAD.SQL file contained in the same directory as this file.
  2. Ensure that you have a properly configured System Datasource using ODBC Data Source Administrator orensure that you have a database that is accessible from IIS.
  3. From a command window, create the necessary tables in your database. For example:
    C> isql -d <mydatabase> -i upload.sql -Usa -P
  4. Modify the samples to use the SQL Server database rather than Access. There are two files to be modified: "UploadToDatabase\Simple\formrespdb.asp" and "UploadToDatabase\Intermediate\mformrespdb.asp". In both files, look for the string beginning "For SQL Server Users".
  5. Comment out the Access-based rsBlob.open
  6. Un-comment the SQL Server-based rsBlob.open

Setup Instructions for Oracle:

Creating the tables

  1. Use the Oracle Schema Manager to create two new tables named "SimpleBlobTable", and "IntermediateBlobTable".
  2. In each table create a column named "ID" with a datatype of "NUMBER (7,0)", set as the primary key.
  3. In each table create a column named "FILECOL", with a datatype of "LONG RAW".
  4. In the "IntermediateBlobTable" table create columns named "Author" and "Descrip" with datatypes of VARCHAR(50).
  5. The "LONG RAW" data type was tested with Oracle 7 & 8, Oracle reccomends using the "BLOB" data type in new applications.

Use SQL*Net Easy Configuration tool to create an alias for the server you wish to access if it has not been done
already. Refer to Microsoft KB Article Q193225, for more information.

Creating the DSN

  1. Using the Control Panel, Open the ODBC Data Source Administrator
  2. Click on the "System DSN" tab.
  3. Select "Add..."
  4. Select "Microsoft ODBC for Oracle Driver "
  5. Click on "Finish"
  6. Enter a Data Source name of "OracleUpload"
  7. Enter the User name (such as SYS) to access the database
  8. Enter the SQL*Net server alias for the server you want to access
  9. Click on "OK" and your database is ready to use.

Database "docmgmnt.mdb" Samples - *Located within Samples\applications\Docmanager\database
Sample Application: (Advanced Document Manager)

  1. Find the UPLOAD.MDB file contained in the same directory as this file.
  2. Using the Control Panel, Open the ODBC Data Source Administrator
  3. Click on the "System DSN" tab.
  4. Select "Add..."
  5. Select "Microsoft Access Driver (*.MDB)"
  6. Click on "Finish"
  7. Enter a Data Source name of "docmgmnt"
  8. Click on "Select..." and navigate to the location of the docmgmnt.MDB file.
  9. Click on "OK" and your database is ready to use.


Legal Information

Information in this document is subject to change without notice. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Software Artisans, Inc. If, however, your only means of access is electronic, permission to print one copy is hereby granted.

Copyright © 2000 - 2010 Software Artisans, Inc. All rights reserved.

Software Artisans, the Software Artisans logo, SA-FileUp, SoftArtisans FileUp, SoftArtisans FileUp Standard Edition, SoftArtisans FileUp Professional Edition, SoftArtisans FileUpEE, SoftArtisans FileUp Enterprise Edition, SA-JFile, SoftArtisans JFile, SA-XFile, SoftArtisans XFile, SA-Archive, SoftArtisans Archive, SA-SMTPmail, SoftArtisans SMTPmail, SA-FileManager, SoftArtisans FileManager, SA-Admin, SoftArtisans Admin, SoftArtisans ImgWriter, SoftArtisans ExcelWriter, SoftArtisans ExcelWriterEE, SoftArtisans ExcelWriterSE, SoftArtisans ExcelWriterLE, SoftArtisans ExcelWriter Desktop, SoftArtisans WordWriter, SA-FileManagerTX, SoftArtisans FileManagerTX, SA-SessionPro, SoftArtisans SessionPro, SA-Check, and SoftArtisans Check are all trademarks of Software Artisans, Inc. in the United States and/or other countries.

SoftArtisans and the SoftArtisans logo are registered trademarks of Software Artisans, Inc.

Microsoft, MS-DOS, MS, Windows, Windows NT, ActiveX, JScript, Microsoft Press, Visual Basic, Visual C++, Visual J++, Win32, and Win32s are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

Alpha AXP is a trademark of Digital Equipment Corporation.

Pentium is a registered trademark of Intel Corporation.

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

Netscape, Netscape Navigator, and the Netscape N logo are registered trademarks of Netscape Communications Corporation in the United States and other countries.

Other product and company names mentioned herein may be the trademarks of their respective owners.


Browser Neutral Upload - Using Client-Side Controls

In some cases, you need to supply different client-side components based on browser dependencies. By using ASP's BrowserType server Object, you can implement both types of client side components, Java Applets or Active-X Controls.

Example:

<% '--- Create an instance of the Standard IIS Server Component. '--- This
      component uses the Browsercap.ini to obtain browser capabilities. Set Browse = Server.CreateObject("MSWC.BrowserType")
      '--- If the browser supports Active-X Controls, XFile is used. If Browse.ActiveXControls
      Then ' SA-Xfile Code '--- If the browser does not support ActiveX Controls, JFile
      is used. Else 'JFile Code End IF %>

This can also be applied to downloading. Check out the samples provided as part of the FileUpdistribution. See Programmer's Samples for a list of the contents of the Samples directory.


A Simple Upload in ASP.NET

FileUp includes many sample ASP.NET applications in both C# and VB.NET. To run the samples, open a browser window and enter the URL http://localhost/safileupsamples. The sample code is in the folder FileUp\Samples.
To allow file uploads, NTFS permissions must be set appropriately for FileUp's temporary and destination directories. For more information, see Setting Appropriate Security.

Here is a simple HTML form that uploads a file:

<HTML> <HEAD> <TITLE>Please Upload Your File</TITLE> </HEAD>
      <BODY> <form enctype="multipart/form-data" method="post"
      action="formresp.aspx"> Enter filename to upload: <input type="file"
      name="f1"><br> <input type="submit"> </form>
      </BODY> </HTML>

When using an HTML form to upload files, the form submitting the file must contain:

  • The <form> tag attribute enctype="multipart/form-data".

  • An <input type="file"> tag, including a name attribute.

The form uploads the file to formresp.aspx (specified by the <form>tag's action attribute). Formresp.aspx contains the following code:

<%@ Page Language="VB" Explicit="True" Strict="True" Debug="True" Trace="False"
      %> <%@ Import Namespace="SoftArtisans.Net" %> <script runat="server">
      Sub Page_Load() Dim oFileUp As New FileUp(Context) oFileUp.Path = "C:\temp"
      oFileUp.SaveAs "C:\uploads\upload.out" oFileUp.Dispose() End Sub </script>
      <HTML> <HEAD> <TITLE>SoftArtisans .NET FileUp 2-Tier Upload Sample</TITLE>
      </HEAD> <BODY> Thank you for uploading your file.<br> Total Bytes
      Written: <%=oFileUp.TotalBytes%> </BODY> </HTML>

The following lines process the upload request, and save the uploaded file

  • <%@ Import Namespace="SoftArtisans.Net" %>
    Imports the "SoftArtisans.Net" namespace to the ASP.NET page. The FileUp objects are in this namespace.

  • Dim oFileUp As New FileUp(Context)
    Creates an instance of the FileUpobject.

  • oFileUp.Path= "C:\temp"
    Sets a temporary directory for the upload on the Web server. Always set the path property immediately after creating an instance of FileUp

  • oFileUp.SaveAs"C:\temp\upload.out"
    Saves the uploaded file on the Web server as "C:\uploads\upload.out".

The following optional line retrieves the TotalBytesproperty and displays it to the user:

Total Bytes Written: <%=oFileUp.TotalBytes%>

When you are finished using an instance of FileUp under .NET, always call FileUp.Dispose(). This ensures thorough cleanup of temporary files.

oFileUp.Dispose()

Setting the Path Property

The Path propery must be set before referencing any variables on the form. As soon as a form element is referenced, FileUp will read in the entire contents of the HTTP post, including all form elements and files. Therefore, if you set Path after referencing a form element, by the time the Pathproperty is set, all of the Form data will have been read, and the cache files created, rendering the Path assignment meaningless.

If you do not set the Path property, FileUp will cache the upload in the server's default directory for cached files.

FileUp Namespace

The FileUp objects are in the SoftArtisans.Net namespace. The objects can be referenced as fully qualified names, such as SoftArtisans.Net.FileUp. To minimize typing and errors, use an Import directive to import the namespace to the ASP.NET page. This allows you to reference objects by name alone, without the namespace prefix.

If you are coding directly in the .aspx page, following the Page directive, include:

<%@Import namespace="SoftArtisans.Net"%>

If you are coding in the "code behind" page (.aspx.vb or .aspx.cs), include an Imports or Using statement at the top of the "code behind" page:

In VB.NET: Imports SoftArtisans.Net
In C#:	  using SoftArtisans.Net

Summary

  • To upload files, there must be two elements on the form:

    • The <form> tag attribute enctype="multipart/form-data".

    • An <input type="file"> tag, including a name attribute.

  • To process the form:

    1. Create an instance of the FileUpobject.
    2. Invoke the .SaveAs method and specify a filename.

  • When you are finished using an instance of FileUp under .NET, always call FileUp.Dispose().

  • After the upload is processed on the server, you can retrieve upload properties such as the total size of the upload.

Top


The .UPLX file extension

Why .uplx?

FileUp's HttpModule is a request pre-processor. It's function is to intercept the request before it is handled by ASP.NET and before any script can be executed. The HttpModule has been designed to handle only requests to pages that use the .uplx file extension, thereby freeing regular aspx page from being unnecessarily pre-processed by the module.

Which pages need to be renamed?

Only aspx pages need to be changed to .uplx. Code-behind pages that would have the extensions .aspx.vb and .aspx.cs do not need need to be changed to uplx.vb or uplx.cs, but they can be. The important thing is that the the presentation page (uplx) can successfully be connected to it's own code-behind via the "src" or "codebehind" attributes of the page directive on the .uplx page.

Notes on Visual Studio.NET as a development environment.

In order to benefit from intellisense and other features of development environments like Visual Studio.NET, you may want to intitially write your code using the aspx extension and then rename it to uplx for testing and production. You will need to be aware that when you run your code using the aspx extension, that the FileUp HttpModule will not preprocess the request. As such, this will not be an accurate picture of the behavior of your application regarding performance, caching location and caching permissions.


Security Considerations in ASP.NET

Copyright © 2010 SoftArtisans, Inc. All rights reserved.


SoftArtisans(tm) FileUp(tm) License Agreement
Single Server License

IMPORTANT: READ THE FOLLOWING TERMS AND CONDITIONS
CAREFULLY.

THESE TERMS AND CONDITIONS CONSTITUTE THE ENTIRE LEGAL
AGREEMENT BETWEEN YOU AND SOFTARTISANS, INC. ("SOFTARTISANS")
CONCERNING THE PROPRIETARY FILEUP(tm) SOFTWARE
PROGRAM (THE "PROGRAM") AND THE ACCOMPANYING USER
DOCUMENTATION (THE "DOCUMENTATION").

1. GRANT OF LICENSE. SoftArtisans grants you a non-exclusive license to install
and use one (1) copy of the Program on a single network server computer owned or
controlled by you. You may transfer the Program from one network server computer to
another, so long as you erase it from the old computer before loading it into the new one.
You may install and use the Program within your own organization only.  You may not
reverse-engineer, disassemble, or decompile the Program. You may copy the
Documentation for your own use.  You may make a single backup copy. Resale or
sublicensing is prohibited.

2. OWNERSHIP. The Program is a proprietary product of SoftArtisans or its
suppliers, and is protected under U.S. copyright law and international treaties. Any copy
of the Program made by you in accordance with this Agreement shall contain Software
Artisans's copyright notices. All intellectual property rights in and to the Program are
retained by SoftArtisans or its suppliers. SoftArtisans(tm) and SA-FileUp(tm) are
trademarks of SoftArtisans, Inc.

3. REGISTRATION. During registration and unregistration of this software, certain
diagnostic information may be transmitted to SoftArtisans. No information is
transmitted during execution of the component - only during registration and
unregistration. The following information is collected: HRESULT of registration,
Username, Computername, Domainname, Time Zone, OS Version, Locale Id, Browser
Version, Source IP Address and CPU Count. The transmitted information is kept confidential
per the terms of our privacy policy, available at:
    http://www.softartisans.com/privacypolicy.html

4. TERM. This Agreement is effective upon your indicating your assent to its terms and
conditions in the manner specified above and shall continue until terminated. You may
terminate this Agreement at any time by deleting all copies of the Program and
Documentation, and any portions thereof, from the computer or network server on which
they are installed and destroying all such copies. SoftArtisans may terminate this
Agreement if you breach any term of this Agreement. You will delete and destroy all
existing copies of the Program and Documentation, and any portions thereof, on
termination of this Agreement.

5. LIMITED WARRANTY. SoftArtisans warrants that for a period of thirty (30)
days from delivery (the "Warranty Period") the Program shall be free from defects in the
media on which it is provided. SoftArtisans does not warrant that your use of the
Program will be uninterrupted or error free. If, during the Warranty Period, the Program
does not meet this limited warranty, you may contact SoftArtisans and Software
Artisans shall, at its option, either replace the Program or refund your purchase price. The
foregoing constitutes your sole and exclusive remedy for breach by SoftArtisans of
any warranties (express or implied) made under this Agreement. This limited warranty is
void if failure of the Program has resulted from accident, abuse, or misapplication. Any
replacement Program will be warranted for thirty (30) days from your date of receipt.
EXCEPT FOR THE WARRANTIES SET FORTH ABOVE, THE PROGRAM AND
THE DOCUMENTATION ARE LICENSED "AS IS," AND SoftArtisans
DISCLAIMS ANY AND ALL OTHER WARRANTIES, EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND
NONINFRINGEMENT. Some states do not allow the exclusion of implied warranties or
limitations on how long an implied warranty may last, so the above limitations and
exclusions may not apply to you. This warranty gives you specific legal rights, and you
may also have other rights which vary from state to state.  For warranty claims, contact
SoftArtisans at the email or post addresses set forth below.

6. LIMITATION OF LIABILITY. SoftArtisans's and its suppliers' cumulative
liability to you and all other parties arising out of or relating to this Agreement shall not
exceed the license fee paid by you to SoftArtisans for the use of the Program.
Neither SoftArtisans nor its suppliers shall be liable for any indirect, special,
incidental or consequential damages or similar damages, including lost profits or lost data
arising out of the use or inability to use the Program, even if SoftArtisans has been
advised of the possibility of such damages. Some states do not allow the limitation or
exclusion of liability for incidental or consequential damages, so the above limitation or
exclusion may not apply to you.

7. U.S. GOVERNMENT LICENSES. The Program and the Documentation are provided
with restricted and limited rights for purposes of government contracting and
subcontracting. Use, duplication or disclosure by the Government is subject to restrictions
as set forth in Subparagraph 252.227-7013(c)(1)(ii) (Rights in Technical Data and
Computer Software)of the Department of Defense Federal Acquisition Regulations
Supplement or Subparagraphs 52.227-19(c)(1) and (c)(2) Commercial Computer
Software - Restricted Rights) of Title 48 of the Code of Federal Regulations, as
applicable. Contractor/manufacturer is SoftArtisans, Inc., PO Box 42, Brookline,
MA 02446 USA.

8. EXPORT ASSURANCES. You may not download or otherwise export or re-export
the Program or any underlying information or technology except in full compliance with
all United States and other applicable laws and regulations, including without limitation,
the United States Export Administration Act, the Trading With the Enemy Act, the
International Emergency Economic Powers Act and any regulations thereunder. Any
transfer of technical data outside the United States by any means, including the Internet,
is an export which is subject to export control requirements under US law.

The Program may not be downloaded or otherwise exported or re-exported (i) into (or to
a national or resident, wherever located, of) Cuba, Libya, Bosnian Serb-occupied portions
of Bosnia and Herzegovina, North Korea, Iran, Iraq, Angola, Syria or any other country
to which the US prohibits exports of goods or technical data; or (ii) to anyone on the US
Treasury Department's Specially Designated Nationals List or the Table of Denial Orders
issued by the Department of Commerce.

By downloading or using the Program, you are agreeing to the foregoing and you are
representing and warranting that you are not located in, under the control of, or a national
or resident of any such country or on any such list or table.

9. ASSIGNMENT. You may assign your rights under this Agreement to another party if
the other party agrees to accept the terms of this Agreement, and you either transfer all
copies of the Program and the Documentation, whether in printed or machine-readable
form (including the original), to the other party, or you destroy any copies not transferred.
Before such a transfer, you must deliver a hard copy of this Agreement (which is
available on SoftArtisans’ Web site) to the recipient.

10. GOVERNING LAW. This Agreement shall be governed by the substantive laws of the
Commonwealth of Massachusetts and US federal law. The United Nations Convention
for the International Sale of Goods shall not apply to this Agreement.

Should you have any questions concerning this Agreement or if you desire to contact
SoftArtisans for any reason, please contact: SoftArtisans, Inc.
Telephone: +1-617-738-0777; FAX: 617-738-6278; Mail: P.O. Box 42, Brookline, MA
02446 USA. E-mail: info@softartisans.com.


Features and Benefits

Quick Install or Upgrade

Release Notes

Version Differences

All Documentation

Sample Code

www.softartisans.com

The Standard in Transactional File Uploads and Secure Downloads

Version 3.43

June 2002

Thank you for using SoftArtisans FileUp™ , the standards-based File Upload Component for Microsoft's Internet Information Server.

Features and Benefits

SoftArtisans FileUp™ allows users with a Web browser to upload or transmit files from their local hard disk to a Microsoft Internet Information Server (IIS) Web server. Files can be of any format, such as Word documents, images or plain text and of any size. FileUp can also be used to download files from an IIS Web server to a client browser.

Developers can use SoftArtisans FileUp to receive and process user input, while staying within the context of their Active Server application.

Key Features:

  • Server-side component - requires no software be installed on user's PC
  • Fully scriptable by Active Server Pages (ASP)
  • Compliant with HTML 3.2 and Internet standard RFC 1867
  • Unicode support of form values and file names.
  • Works with Netscape 2.x and above
  • Works with the following versions of Internet Explorer
    • IE 4.0 and IE 5.0, or later
    • IE 3.02a (16-bit)
    • IE 3.02 (32-bit) but requires the File Upload Add-on available free from Microsoft.
  • Transactional processing of uploads and downloads within Microsoft Transaction Server (MTS). Note: To use SoftArtisans FileUp transactionally, apply NT Service Pack 5 or later. We do not support transactional use of SoftArtisans FileUp with earlier versions of Service Pack.
  • Performance Monitor Counters allow you to precisely monitor upload and download performance. For example, upload size and duration can be precisely monitored.
  • Server-side progress indicator lets you monitor the progress of your uploads.
  • MacBinary Decoding. For Macintosh clients, full MacBinary is supported. Files uploaded from a Macintosh will be stored with proper NTFS streams intact.
  • Recursive Directory Uploads. Using SoftArtisans FileUp in conjunction with our client-side tools (SoftArtisans JFile and SoftArtisans XFile), entire directory trees can be uploaded in a single, easy operation.
  • Uploads to memory. Uploads can be stored in memory, rather than disk for better performance and security.
  • Includes three bonus components:
    • SoftArtisans Archive, a programmer's tool for the creation and extraction of ZIP and CAB archives
    • SoftArtisans FileManager, an easy-to-use component that provides all your file management needs
    • SoftArtisans SmtpMailLE, a light version of our full-featured SMTP E-mail client

Requirements:

Operating System | Web Server | Active Server Pages (ASP) | Service Pack
Windows 95 | Personal Web Server | ASP DLL Version 1.15.14.0 or later | N/A
Windows 98 | Personal Web Server | ASP DLL Version 1.15.14.0 or later | N/A
WinNT Server | IIS 3 and higher * | ASP DLL Version 1.15.14.0 or later | 3.0 and up **
 | Apache 1.3.4, 1.3.6 | Chili!Soft ASP Version 1.2 and up | N/A
 | Netscape Enterprise Server | Chili!Soft ASP Version 1.2 and up | N/A
 | Netscape FastTrack Server 3 | Chili!Soft ASP Version 1.2 and up | N/A
WinNT Workstation | Peer Webserver/Personal Web Server * | ASP DLL Version 1.15.14.0 or later | 3.0 and up **
 | Apache 1.3.4, 1.3.6 | Chili!Soft ASP Version 1.2 and up | N/A
 | Netscape Enterprise Server | Chili!Soft ASP Version 1.2 and up | N/A
 | Netscape FastTrack Server 3 | Chili!Soft ASP v3.04 | N/A
Windows 2000 | IIS 5.0 | ASP DLL Version 5.0 or later | N/A

* Highly recommended (but not essential):

  • If you are using IIS Version 3, use Service Pack 3 and the ASP Hotfix (KB article Q165335).
  • If you are using IIS Version 4, use Service Pack 5.0 or later.

** If you plan to use SoftArtisans FileUp'stransactional features, install the following,

  • Windows 2000

    Or:
  • NT 4.0 with IIS 4 or higher and Service Pack 5 or higher. SoftArtisans FileUp's transactional feature does not work with Service Pack 3, and is only supported with Service Pack 5 or higher. Non-transactional use of SoftArtisans FileUp with IIS3 and IIS4 is fully supported.
  • Microsoft Transaction Server (MTS)

ALPHA ONLY If you will be uploading to an Access database, use the Microsoft Access Driver Alpha Version 3.50.390700 or later. This is available from http://www.microsoft.com/data.

If you intend to save files in a database (using SaveAsBlob or TransferBlobmethods), it is highly recommended that you install the latest Microsoft drivers. The driver package is available for free for all versions of IIS at http://www.microsoft.com/data. Choose to download MDAC 2.0 or later. MDAC includes updates to ADO, OLEDB, and related ODBC drivers. As of this writing, the latest version is "Microsoft Data Access Components 2.1".

Pricing:

  • Site, Enterprise, and OEM licenses are available. Please contact SoftArtisans, Inc directly for further information.
  • Please check The SoftArtisans' web sitefor the latest ordering information.

Top

Quick Installation or Upgrade

For complete instructions about installing SoftArtisans FileUp, including tailoring your installation and security considerations, please see the complete documentation.

Installation of SoftArtisans FileUp consists of simply running the setup.exefile included with this distribution.

ALPHA ONLY The Version of SoftArtisans FileUp for Compaq Alpha Processors does not come with an automated InstallShield installation procedure. You must manually install SoftArtisans FileUp using these simple steps:

  1. Copy SAFILEUP.DLL to an executable directory of IIS
  2. Copy SAFILMGR.DLL to an executable directory of IIS
  3. Register SAFILEUP.DLL in the System Registry
  4. Register SAFILMGR.DLL in the System Registry

This is documented in the Installation section of the documentation under "Installing for the First Time".

SoftArtisans FileUp works well with IIS Version 4 and the NT Option Pack.

For IIS Version 3 users, please note that you will need Version 1.0b or later of Active Server for this release of SoftArtisans FileUp. The latest version of IIS can be downloaded from Microsoft's IIS Web Site (http://www.microsoft.com/iis) . To determine your current version of Active Server:

  • Open Windows Explorer.
  • Navigate to \winnt\system32\inetsrv\asp. (Replace \winnt by your system root)
  • Right-click on ASP.DLL, and select Properties.
  • Choose the Version tab. It should read 1.15.14.0 (or later).

SoftArtisans FileUp will not work with an earlier version of Active Server Pages.

When installing SoftArtisans FileUp, it may be necessary to stop and restart the WWW Publishing Service.

Upgrading from the Evaluation or Previous Version

If you've previously used the evaluation version of SoftArtisans FileUp and are now upgrading to the full release, note the following:

  • Before installing the complete, non-evaluation version, be sure to uninstall the evaluation version. This will remove all directories and program files. Use either the shortcut from the "SoftArtisans SoftArtisans FileUp" start menu, or use the Control Panel's "Add/Remove Programs" application
  • For upgrading on Windows NT 4, you must manually remove the SoftArtisans FileUp Package using Transaction Server Explorer before installing the full version.
  • If SoftArtisans FileUp has already been loaded by IIS, you will be prompted by the installation procedure to reboot your server.
  • We recommend rebooting the server after upgrading.
Top

Release Notes

New features are listed in Version Differences.

Specific issues with this release include:

  • The Progress Indicator does not work with Windows 98; only with Windows 2000 and Windows NT4.

  • The /SAFileUpDocs and /SAFileUpSamples virtual directories will not have script permissions set by default under Windows 2000 only. These must be added manually. See Documentation Setup and Sample Code later in this file for details.

  • Uninstalling the product will not remove the /SAFileUpDocs and /SAFileUpSamplesvirtual directories. These must be removed manually. Also, the MTS Package must be removed manually using the Transaction Server Explorer. These are the only two uninstallation items that must be manually performed.

  • Under Windows 95 and Windows 98, the automated installation may not create the /SAFileUpDocs and /SAFileUpSamples virtual directories. See Documentation Setup and Sample Code later in this file.

  • The SaveAsDialog sample will not behave correctly with all versions of Internet Explorer. In some cases, such as with Text and HTML files, the browser will render the file and not give an opportunity to open a "Save As" dialog box. In other cases, the browser will refuse to populate the dialog box with the correct preset name. Microsoft has been made aware of these browser issues. As SoftArtisans FileUp is a server-side component, there is no reliable means of circumventing these specific browser issues. Instead, we have developed client-side tools, such as SoftArtisans JFile to enhance the standard browser. Please check our web site for the latest details.
Top

Version Differences

Differences Between v3.41 and v3.43

  • Documentation updates:
    • FileManager File object properties: FileSystem, ImageColor, ImageHeight, ImageWidth, Permissions.
    • FileManager Folder object property: Permission.
    • SMTPMail property: CodePage.

Differences Between v3.4 and v3.41

  • In FileUp Object, when caching temporary files, intelligent path searching is implemented. Check principal object's Path property.
  • FileManager changes:
    • New RSA encryption types added: SARSAHIGH (3) and SARSALOW (4).
    • Fixed: Two Fish encryption/decryption failure on files larger than 1K.
    • Fixed: Failure of RevertToSelf method in Visual Basic.
    • Fixed: Trustee names on a remote NT member-server could not be displayed.
    • Fixed: Access Control List (ACL) corruption after FileManager applied changes to ACLs with Windows NT system.
  • In SMTPMail object, enumeration type CHARSET changes to SACHARSET.

Differences Between v3.32 and v3.4

  • Bug fix: Random commas inserted in form value larger than 64K.
  • Characters invalid for Windows file system will automatically be replaced with underscore ("_"). Useful for uploads from Mac or Unix/Linux systems.
  • New functionality for Path property of the main FileUp object and SAFile object (individual file). User can set Path property multiple times. The Save method will use the path last assigned to the property.

    Example:

    <%
    set upl = Server.CreateObject("SoftArtisans.FileUp")
    '--- Set the path for the temporary cache of the upload
    upl.Path = "c:\temp"
    if not upl.IsEmpty then
       upl.Path = upl.form("usersDirectory")
    upl.form("file1").Save
    upl.Path = "C:\differentDirectory"
    upl.form("file2").Save
    end if
    %>

Differences Between v3.31 and v3.32

  • Bug fix: Indices can now be used to iterate through the elements of the FormEx collection.
  • New property added to both the main FileUp object and the SAFile object (individual file):
    • ShortFileName property - returns the user's original filename without any associated path information.
  • New FileUp object property MaxBytesToCancel allows you to abort very large uploads before they reach the server, reducing the threat of a DoS (Denial of Service) attack on the server.

Differences Between v3.3 and v3.31

  • The issues that occured when uploading an extraordinarily large amount of form elements or a form element with a very long name have been resolved.
  • There has been a fix to SoftArtisans Archive, which is bundled with SoftArtisans FileUp:
    • SoftArtisans Archive 1.0.7.6 issue with archiving files containing folder(s) has been resolved in SoftArtisans Archive 1.0.7.7.

Differences Between v3.2.0.8 and v3.3

  • Improved performance for SSL file transfer. Tested with 1.5G size. Maximum buffer size is 204,800.
  • Developed a workaround for an issue with particular IE5.0: when used with authentication, this version of IE5.0 corrupts the header. FileUp works around this issue and saves the files correctly.
  • PerserveMacBinary was added for flexibility when uploading files from Mac. If files are in Macbinary format, user can choose to save data fork only or the whole uploading stream.
  • Issues affecting FileManager enumerating root directories or files with Win95/98/Me platform have been resolved.
  • Files created with Archive no longer have issues hanging with certain directories.
  • SoftArtisans Archive has a new means of zip file creation that will preserve the zip files' path. You can access this feature by setting ArchiveType to "3". SoftArtisans Archive documentation will be updated at a later date.
    • Entries property and Exists method are not supported. You cannot modify the zip; you should only create the zip or expand the whole zip.
    • There is no change in the previous zip function (ArchiveType= 1),so preserving directories is still not supported.< /li>< /li>
  • Issues affecting SaveAsBlob method and Windows2000 Service Pack 2 have been resolved when FileUp is deployed into MTS/COM+ as a library package.
Top

All Documentation

Installation of the documentation is automatic with Windows 2000, Internet Information Server (IIS) Version 3 and Version 4. When installing for use with IIS Version 4, you can also use the setup wizard of the Microsoft Management Console (MMC).

To install the SoftArtisans FileUp documentation using MMC:

  • Right click on the "Default Web Site."
  • Select New->Virtual Directory to start the Virtual Directory Wizard.
  • As the alias, enter "SAFileUpDocs" (without quotation marks)
  • For the physical path, use the "Browse.." button and select C:\Program Files\Software Artisans\SoftArtisans FileUp\Documentation".
  • Accept the defaults and click on the "Finish" button.
  • Note: Starting with V2.2, the SoftArtisans FileUp documentation requires Execute Script (ASP) permissions on the SAFileUpDocs directory. This is default for IIS4, but must be manually selected for IIS3. If you upgrading from an earlier version , the install procedure may fail to change the directory from non-script to script. If necessary, use MMC, select the /SAFileUpDocs virtual directory and change the properties from "none" to "script".

Top

Sample Code

There are numerous code samples covering all aspects of SoftArtisans FileUp and SoftArtisans FileManager, including upload to a file, upload to a database, download from a file, and download from a database. We are constantly enlarging our code sample base; please let us know if we can add other samples.

Installation of the sample code is automatic with Windows 2000, Internet Information Server (IIS) Version 3 and Version 4. When installing for use with IIS Version 4, you can also use the setup wizard of the Microsoft Management Console (MMC).

To install the Code Samples, using MMC:

  • Right click on the "Default Web Site."
  • Select New->Virtual Directory to start the Virtual Directory Wizard.
  • As the alias, enter "SAFileUpSamples" (without quotation marks)
  • For the physical path, use the "Browse.." button and select C:\Program Files\Software Artisans\SoftArtisans FileUp\Samples".
  • Accept the defaults and click on the "Finish" button.

Top


Setting Appropriate Security

  • ASP Security Settings
  • ASP.NET Security Settings
  • The ISAPI Filter and the HttpModule
  • General Guidelines
ASP Security Settings

In ASP, FileUp executes in a specific user context:

  • IUSR_MACHINENAME (The default anonymous user account)

    • OR

  • An authenticated user account

To allow uploads, the IUSR_MACHINENAME or authenticated user must have Read, Write, and Modify NTFS permissions for FileUp's physical temporary and destination folders.

Read, Write, and Modify are NTFS permissions and are required for the physical destination folders only. These permissions are not required in IIS.

An upload's destination folder is set in code by FileUp.Pathor FileUp.SaveAs. The temporary directory for an upload can be set in code by the property FileUp.Path. If you do not assign a value to FileUp.Path, uploads will be cached in the system's default directory for cached files, which is determined by the system environment variable TEMP.

To change the system's default directory for cached files, reset the TEMP environment variable, as follows:

  1. Open the Control Panel.
  2. Select System.
  3. Select the Advanced tab.
  4. Click Environment variables...
  5. Select TEMP from the System Variables list.
  6. Click Edit.
  7. Enter a new Variable Value, and click Ok.
If UseMemoryis set to True, FileUp will not write temporary files and it is not necessary to set permissions for a temporary directory.

If the upload destination folder is a virtual directory, a malicious user may be able to upload an infected file to the directory and launch it through the Web. To prevent this, use a folder that is not a virtual directory as the upload destination location.

Top

ASP.NET Security Settings

In ASP.NET, if impersonation is disabled - as it is by default - FileUp executes in the context of the ASPNET account or an authenticated user account. To allow uploads, the ASPNET account or authenticated user must have Read, Write, and Modifypermissions for FileUp's temporary and destination folders.

Read, Write, and Modify are NTFS permissions and are required for the physical destination folders only. These permissions are not required in IIS.

An upload's destination folder is set in code by FileUp.Pathor FileUp.SaveAs. The temporary directory for an upload can be set in code by the property FileUp.Path. If you do not assign a value to FileUp.Path, uploads will be cached in the system's default directory for cached files, which is determined by the system environment variable TEMP.

To change the system's default directory for cached files, reset the TEMP environment variable, as follows:

  1. Open the Control Panel.
  2. Select System.
  3. Select the Advanced tab.
  4. Click Environment variables...
  5. Select TEMP from the System Variables list.
  6. Click Edit.
  7. Enter a new Variable Value, and click Ok.

If you enable impersonation, FileUp will execute in the IUSR_MACHINENAMEor authenticated user context and you can set permissions as you would for ASP. Under ASP.NET impersonation is controlled in the .NET configuration file for your Web application - web.config or machine.config (For information about these files, see Installing FileUp for ASP.NET.). To enable impersonation, set impersonate to true in the identity node of web.config or machine.config:

<identity impersonate="true" userName="" password=""/>

The following is a sample web.config file with impersonate set to true:

<configuration> <system.web> <compilation numRecompilesBeforeAppRestart="15"/>
      <compilers> </compilers> </compilation> <httpHandlers> <add
      verb="*" path="*.uplx" type="System.Web.UI.PageHandlerFactory"/> </httpHandlers>
      <httpModules> <add name="FileUpModule" type="SoftArtisans.Net.FileUpModule,FileUpModule,
      Version=x.x.x.x, Culture=neutral,PublicKeyToken=f593502af6ee46ae"/> </httpModules>
      <identity impersonate="true" userName="" password=""/> </system.web>
      </configuration>
If UseMemoryis set to True, FileUp will not write temporary files and it is not necessary to set permissions for a temporary directory.

If the upload destination folder is a virtual directory, a malicious user may be able to upload an infected file to the directory and launch it through the Web. To prevent this, use a folder that is not a virtual directory as the upload destination location.

Top

The ISAPI Filter and the HttpModule

FileUp's interceptors - the ISAPI filterand the HttpModule - cache request data before it is processed by ASP or ASP.NET.

The ISAPI filter and the HttpModule write to the hard drive as the local SYSTEM account, and can write to any directory on the server. The ISAPI filter/HttpModule temp directory must be on a local drive, not on a network shared drive, because the SYSTEM account does not have access to network drives.

The location of the temporary directory can be configured in the Windows registry. By default, the cache location is the system's default directory for cached files, which is determined by the system environment variable TEMP. To set a different ISAPI filter temp directory:

  1. Open the Start menu, and select Run.
  2. Enter regedit and click Ok.
  3. Open HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\SA-FileUp\Parameters.
  4. Right-click IsapiTempDir and select Modify.
  5. In Value Data, enter the path and folder name.

To set a different HttpModule temp directory:

  1. Open the Start menu, and select Run.
  2. Enter regedit and click Ok.
  3. Open HKEY_LOCAL_MACHINE\SOFTWARE\Software Artisans\SA-FileUp\Parameters.
  4. Right-click FileUpTempDir and select Modify.
  5. In Value Data, enter the path and folder name.
To change the system's default directory for cached files, reset the TEMPenvironment variable, as follows:
  • Open the Control Panel.
  • Select System.
  • Select the Advanced tab.
  • Click Environment variables...
  • Select TEMP from the System Variables list.
  • Click Edit.
  • Enter a new Variable Value, and click Ok.

Top

General Guidelines
  • Don't allow write access to critical directories such as "C:\", "C:\WINNT", and "C:\WINNT\System32".

  • Do audit scripts to ensure that ASP developers are writing to correct locations.

  • Do audit scripts to ensure that an instance of FileUp is not created as an Application variable.

  • Do use the Pathproperty to set an appropriate temporary directory. FileUp needs a file cache to function. If the Path property is not set, FileUp will use the default temporary directory of the system.

  • Don't prevent the IUSR_MACHINENAME account (for ASP) or the ASPNET account (for ASP.NET) from reading the system registry, especially the HKEY_CLASSES_ROOT hive.

  • Don't prevent the IUSR_MACHINENAME account (for ASP) or the ASPNET account (for ASP.NET) from reading SAFileUp.DLL.

  • Don't leave the default Everyone-Everything permission on a publicly available Web server.

Top


FileUp Editions

SoftArtisans offers three editions of FileUp:

  • FileUp Standard Edition (FileUpSE)
    FileUpSE quickly and securely transmits files from a local hard disk to a server running Microsoft Internet Information Server (IIS), or to a separate file server which is networked to the Web server. With FileUpSE, you can upload up to 4-GB with minimal server resources.

  • FileUp Professional Edition (FileUpPE)
    FileUpPE combines server-side power of FileUpSE with client-side products for complete file transfer functionality. FileUpPE includes FileUpSE, and the client side tools JFile (a Java applet) and XFile (an ActiveX control).

  • FileUp Enterprise Edition (FileUpEE)
    FileUpEE tackles the multi-faceted needs of any secure file transfer application. FileUpEE easily handles multi-gigabyte file transfers, supports Web farms and functions across firewalls. With no limits on the number or size of files you can upload, FileUpEE solves the server-crippling upload limitations of IIS and ASP.NET.

Feature | FileUp Enterprise | FileUp Professional | FileUp Standard
Secure Web-to-file server transfers | Yes |  |
Send/process SOAP requests | Yes |  |
Allows centralized or replicated secure file storage | Yes |  |
Centrally locate transfer logic | Yes |  |
Audit transfers easily | Yes |  |
Data administration | Yes |  |
File selection GUI | Yes | Yes |
Preset file(s) to/from client | Yes | Yes |
Rich client-side ActiveX control and Java applet | Yes | Yes |
Multi-file progress indicator | Yes | Yes |
File size maximum | Unlimited | 4 Gigabytes | 4 Gigabytes
Bypass ASP.NET, IIS limits | Yes | Yes | Yes
Easy to use | Yes | Yes | Yes
Process all file types | Yes | Yes | Yes
Data integrity | Yes | Yes | Yes
Secure client-to-Web server transfers | Yes | Yes | Yes
Versatile file manipulation | Yes | Yes | Yes
Secure Web-to-file server transfers

Enterprise Edition: Transfer files via HTTP(S) from public Web servers through any number of firewalls to a file server, where sensitive information can remain secure.

Send/Process SOAP requests

Enterprise Edition: Uploads from Web server to file server are submitted as SOAP requests, allowing your firewall to reject all non-SOAP requests. The SOAP request sends all user-submitted form data to the file server with the upload. Choose to have FileUpEE automatically create the SOAP request, or create the request yourself via ASP or ASP.NET.

Allows centralized or replicated secure file storage

Enterprise Edition: Within multi-Web server architectures uploaded files are stored in a central, shared file location. A file that is uploaded to a server in a Web farm is immediately available to be downloaded from any other server in that Web farm. There is no need to replicate data between all of the Web servers. Centrally located, the data can be replicated to multiple file storage areas for additional backup protection.

Centrally locate transfer logic

Enterprise Edition: Application logic specific to the transfer - such as a database connection string - can be optionally contained on a secure centrally located file server. When the application requires modification, the information only needs to be changed on the file server - not on each server in the Web farm.

Audit transfers easily

Enterprise Edition: Create an audit database that details information about the upload/download. Track when files are sent, time of completion, size of files, etc.

Data administration

Enterprise Edition: All files are transferred with fully extensible properties to describe them. And with file size concerns no longer an issue, IT Departments, through minimal scripting, can immediately replicate all files to a disaster recovery system.

File-selection GUI

Enterprise and Professional Editions: Clean, customizable interface for a) multiple file and directory uploads, b) File/Folder list sorting by name, date, or size, c) color parameters for background, buttons, file list box, and text, d) multiple file extension filters and e) directory navigation buttons.

Preset file(s) to/from client

Enterprise and Professional Editions: Preset the client file path for a download or the file to upload from a user's hard disk.

Rich client-side ActiveX control and Java applet

Enterprise and Professional Editions: Access system transfer methods (WinInet, Sockets, URLConnect), support SSL, proxies, and multiple authentication mechanisms, make multiple HTTP Gets or Posts in a single operation, generates events for capture by Internet Explorer or Visual Basic.

Multi-file progress indicator

Enterprise and Professional Editions: Display an accurate progress indicator for both an individual file and the total transfer while uploading and downloading.

File size maximum

Professional and Standard Editions: Transmit files up to 4 gigabytes. Enterprise Edition: There are no limitations on the number or size of files you can upload. Back up entire hard drives in a single step.

Bypass ASP.NET, IIS limits

All Editions: Solve potentially server-crippling upload limitations in ASP.NET and IIS. By intercepting transfer requests with an ISAPI filter, FileUp buffers a small portion of the upload into physical memory, then caches it to disk, before gracefully passing it to IIS on the Web server.

Easy to use

All Editions: Intuitive object models, clear documentation, and extensive working samples make all editions of FileUp - and the bonus tools they include - very easy to use.

Process all file types

All Editions: There are no file type limitations in any of the editions. Transfer .doc, .pdf, .psd and .mpeg files just to name a few.

Data Integrity

All Editions: Verify the integrity of uploaded data when transferring files from a browser to a Web server. Enterprise Edition: Verify data integrity when uploading from browser to Web server or from Web server to file server.

Secure client-to-Web server transfers

All Editions: Uploads from the client to the Web server can be SSL encoded so that the information is encrypted during transmission. In contrast, there is no means for doing that using standard FTP.

Versatile file manipulation

All Editions: Compress uploads and decompress downloads in zip format. Filter files by type, size, and name.


Checksum Property

Object: SoftArtisans.SAFile
Syntax: Checksum
Type: String
Read/Write: Read only
Description:

FileUp generates an MD5 hash of each uploaded file, after it is received on the server. The Checksum property returns a string representing the specified file's MD5 hash. You can use this value to verify the integrity of the uploaded file, by comparing an MD5 hash generated on the client, and the MD5 hash generated by FileUp on the server.

Note: Note that FileUp generates an MD5 hash on the server, not the client. To verify data integrity, you will need a tool that can generate an MD5 hash on the client, such as SoftArtisans FileManager which is included free with FileUp.
See Also: FileManager Checksum Property

Examples:

ASP
'--- Instantiate the FileUp object
Set fileUpload = Server.CreateObject("SoftArtisans.FileUp")
...

'--- Get the client-side hash submitted by the form
clientHash = fileUpload.Form("fileHash")

'--- Now, make a server-side hash with FileUp
serverHash = fileUpload.Form("myFile").CheckSum

Response.Write("<B>Comparing hashes</B><BR>")
Response.Write("<B>Client hash:</B> " & clientHash & "<BR>")
Response.Write("<B>Server hash:</B> " & serverHash & "<BR>")

'--- Compare them to verify file integrity
If StrComp(clientHash, serverHash) = 0 Then
'--- The hashes are the same! File integrity is verified
fileUpload.Form("myFile").Save
Response.Write("... Hashes <B>OK!</B><HR NOSHADE>")
Response.Write("File integrity has been verified,_
and the file has been saved to: " &_
fileUpload.Form("myFile").ServerName & "<BR>")
Else
Response.Write("... Hashes <B>mismatch!</B><HR NOSHADE>")
Response.Write("File integrity cannot be verified " & _
"and will not be saved.")
End If
...
%>
VB.NET
'--- Process the upload
Private Sub ProcessUpload()

'--- Declare an object for FileUp
Dim fileUpload as FileUp

'--- This StringBuilder will be used to display results
Dim res As New System.Text.StringBuilder()

Try

'--- Instantiate FileUp
fileUpload = New FileUp (Context)

'--- When the HttpModule is used, the path property does not
'--- affect caching location. Instead it is merely used
'--- as a placeholder to store the path to the directory
'--- where the files will be saved.
fileUpload.Path = "C:\UploadDir

'--- Get a reference to the uploaded file field
Dim file As SaFile = CType (fileUpload.Form ("myFile"), SaFile)

'--- Check to be sure there was a file selected in the form
'--- If so, continue processing
If Not (file Is Nothing) Then
If Not (file.IsEmpty) Then

'--- Get the client-side hash submitted by the form
Dim clientHash As String
clientHash = fileUpload.Form("fileHash").ToString()

'--- Now, make a server-side hash with FileUp
Dim serverHash As String = file.Checksum

res.Append("Comparing hashes<BR>")
res.Append("Client hash: " + clientHash + "<BR>")
res.Append("Server hash: " + serverHash + "<BR>")

'--- Compare them to verify file integrity
If (String.Compare(clientHash, serverHash) = 0) Then

'--- File integrity is verified
file.Save()
res.Append ("... Hashes OK!")
res.Append ("File integrity has been verified, " + _
"and the file has been saved to: " + _
"file.ServerName + "<BR>")
Else

'--- If the hashes don't match, don't save the file
'--- Explicitly delete it
file.Delete()
res.Append ("... Hashes mismatch!")
res.Append ("File integrity cannot be verified " + _
"and therefore it will not be saved.")
End If

Else
'--- If IsEmpty is true, the file field was left empty
res.Append("There was no file submitted for upload.")
End If

Else
results.Append ("The referenced field does not exist " +_
"or is not of type=""file""")
End If

'--- Display the results on the webform
ltrUploadResults.Text = res.ToString()

Catch ex As System.Exception
'--- If an exception is caught, display the details
ltrUploadResults.Text = "An error has occurred:<br>" + _
ex.Message
Finally
'--- Always call FileUp.Dispose in the finally block
If Not (fileUpload Is Nothing) Then
fileUpload.Dispose()
fileUpload = Nothing
End If

End Try

End Sub
C#
//--- Process the upload
private void ProcessUpload()
{
//--- Declare an object for FileUp
FileUp fileUpload=null;

//--- This StringBuilder will be used to display results
System.Text.StringBuilder res = new System.Text.StringBuilder();

try
{
//--- Instantiate the FileUp object
fileUpload = new FileUp (Context);

//--- When the HttpModule is used, the path property does not
//--- affect caching location. Instead it is merely used
//--- as a placeholder to store the path to the directory
//--- where the files will be saved.
fileUpload.Path = "C:\\UploadDir";

//--- Get a reference to the uploaded file field
SaFile file = (SaFile)fileUpload.Form["myFile"];

//--- Check to be sure there was a file selected in the form
//--- If so, continue processing
if (file != null)
{
if (!file.IsEmpty)
{
//--- Get the client-side hash submitted by the form
string clientHash = fileUpload.Form["fileHash"].ToString();

//--- Now, make a server-side hash with FileUp
string serverHash = file.Checksum;

res.Append("Comparing hashes<BR>");
res.Append("Client hash: " + clientHash + "<BR>");
res.Append("Server hash: " + serverHash + "<BR>");

//--- Compare them to verify file integrity
if (String.Compare(clientHash, serverHash) == 0)
{
//--- File integrity is verified
file.Save();
res.Append ("... Hashes OK!");
res.Append ("File integrity has been verified, " +
"and the file has been saved to: " +
file.ServerName + "<BR>");
}
else
{
//--- If the hashes don't match, don't save the file
//--- Explicitly delete it
file.Delete();
res.Append ("... Hashes mismatch!");
res.Append ("File integrity cannot be verified " +
"and therefore it will not be saved.");
}

}
else
{
//--- If IsEmpty is true, the file field was left empty
res.Append ("There was no file submitted for upload.");
}
}
else
{
res.Append ("The referenced field does not exist " +
"or is not of type=\"file\"");
}

//--- Display the results on the webform
ltrUploadResults.Text = results.ToString();

}
catch(Exception ex)
{
//--- If an exception is caught, display the details
ltrUploadResults.Text = "An error has occurred:<br>" +
ex.Message;
}
finally
{
//--- Always call FileUp.Dispose in the finally block
if (fileUpload != null)
{
fileUpload.Dispose();
fileUpload = null;
}
}
}


Create Method

Object: SoftArtisans.SAFile
Syntax: Create([in] Filename As String)
Description:

This method creates the specified file.

When a path is specified as part of the specified filename ("c:\uploads\file.ext"), it must be a complete path. Relative paths cannot be used.

If no path was previously set, FileUpuses the system-defined Temporary Path (which is returned by the WIN32 GetTempPath() routine). Typically, this is "C:\Temp".

You can set the path by using either the SAFile (file specific) Path property , or by the FileUp (for all files) Path property.

Note: An SaFile object cannot be created when using FileUp in .NET. Therefore, use of this method is not recommended. Use .NET's built-in File I/O classes instead.
Examples:
ASP <%
Set file = Server.CreateObject("SoftArtisans.SAFile")
file.Path = "C:\Temp\"
file.Create "DeleteMe.txt"
file.Create "C:\Empty.txt" %>
ASP.NET N/A - Not recommended


CreateTemp Method

Object: SoftArtisans.SAFile
Syntax: CreateTemp([out] TempFilename As String)
Description:

This method creates a temporary file in the directory specified by the Path property and returns the filename, including the complete path.

Temporary files have the format "SAnnnn.TMP", where nnnnis a unique string.

If the Path property was not previously set, FileUpuses the system-defined Temporary Path (which is returned by the WIN32 GetTempPath() routine). Typically, this is "C:\Temp".

The path may be set through either the SAFile (file specific) Path property or the FileUp (for all files) Path property .

Note: An SaFile object cannot be created when using FileUp in .NET. Therefore, use of this method is not recommended. Use .NET's built-in File I/O classes instead.
Examples:
ASP <%
Set file = Server.CreateObject("SoftArtisans.SAFile")
file.Path = "C:\Temp\"
file.CreateTemp newTempFilename
%>
ASP.NET N/A - Not recommended


programmer_ref_archive

SoftArtisans Archive provides programmers with a tool to create and extract archives in both ZIP and Microsoft Cabinet format. Using Archive, you can:

  • Create a new archive.
  • Add, extract, or delete files from an existing archive.
  • Enumerate the contents of an archive.
  • Sign the archive using Microsoft Authenticode (for .CAB or .EXE files only).

Archive has three objects:

  • Archive Object
  • ArchiveItemCollection Object
  • ArchiveItem Object