FileUpload Control
FileUpload Control
Applications often need to allow users to upload files to the Web server. Although this functionality can be accomplished in asp.net 1.X, it is simpler to use the FileUpload control in asp.net 2.0.
This control makes it easier for users to browse and select files for uploading, including a browse button and a text box for entering a file name. Whenever the user enters a fully qualified file name in the text box, either directly or through the browse button, the FileUpload SaveAs method can be invoked to save to disk.
In addition to the standard members inherited from the WebControl class, the FileUpload control exposes several read-only properties, listed in tables 5-8 and 5-9.
Table 5-8 FileUpload Control Properties
Name |
Type |
Read |
Write |
Description |
Filecontent |
Stream |
X |
|
Returns a Stream object pointing to the uploaded file |
FileName |
String |
X |
|
Returns the name of the file to upload and does not contain path information |
HasFile |
Boolean |
X |
|
If true, indicates that the control has files to upload |
PostedFile |
Httppostedfile |
X |
|
Returns a reference to a file that has been uploaded. Table 5-9 lists the read-only properties that it exposes |
Table 5-9 Httppostedfile Properties
Name |
Type |
Read |
Write |
Description |
ContentLength |
Integer |
X |
|
Returns the file size in bytes of the uploaded file |
ContentType |
String |
X |
|
Returns the MIME content type of the uploaded file |
FileName |
String |
X |
|
Returns the fully qualified name of the file on the client |
InputStream |
Stream |
X |
|
Returns a Stream object pointing to the uploaded file |
All of these properties are described in the following example.
To view the actual use of the FileUpload control, create a Fileuploaddemo Web site. Add a FileUpload control to the page, and then add two asp.net buttons, with the Text property set to save and Display,id, respectively, to Btnsave and Btndisplay. Add two label controls and set the IDs to Lblmesage and Lbldisplay, respectively. Separate the controls with the <br/>html element. Switch to Design view to create a click event handler with a default name in the code-behind file by double-clicking each button. The finished content file is similar to Example 5-11.
Sample 5-11:fileuploaddemo Web site's default.aspx
<%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs"
inherits= "_default"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd XHTML 1.1//en"
"Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" >