ASP.net 2.0 Advanced Control FileUpload Control

Source: Internet
Author: User
Tags file size file system iis save file valid client
Asp.net| Advanced | 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 an <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"
<title> FileUpload Control </title>

<body>
<form id= "Form1" runat= "Server"
<div>
<asp:fileupload id= "FileUpload1" runat= "Server"/>
<BR/>
<asp:button id= "btnsave" runat= "Server" text= "Save" onclick= "Btnsave_click"/>
<asp:button id= "Btndisplay" runat= "Server" text= "Display" onclick= "Btndisplay_click"/>
<BR/>
<BR/>
<asp:label id= "lblmessage" runat= "Server"/>
<asp:label id= "Lbldisplay" runat= "Server"/>
</div>
</form>
</body>
In the code-behind file, add the code highlighted in example 5-12, and the non-highlighted code is automatically created by VS2005.

Sample 5-12:fileuploaddemo Web site's Default.aspx.cs

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.IO; Use stream required

public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{}
protected void Btnsave_click (object sender, EventArgs e)
{
String str = "";
if (fileupload1.hasfile)
{
Try
{
STR + + "uploading file:" + fileupload1.filename;
Save File
Fileupload1.saveas ("c:\\websites\\uploads\\" + fileupload1.filename);
displaying file information
STR + + "<br/> Saved as:" + FileUpload1.PostedFile.FileName;
str + = "<br/> File Type:" + FileUpload1.PostedFile.ContentType;
str = "<br/> File Length (bytes):" + FileUpload1.PostedFile.ContentLength;
str + = "<br/> postedfile File Name:" + FileUpload1.PostedFile.FileName;
}
catch (Exception ex)
{
str = "<br/> <b> Error </b> <br/> Unable to save
C:\\websites\\uploads\\ "+ fileupload1.filename +" <br/> "+ ex. message;
}
}
Else
{
str = "No file uploaded."
}
Lblmessage.text = str;
Lbldisplay.text = "";
}

protected void Btndisplay_click (object sender, EventArgs e)
{
String str = "<u> File:" + fileupload1.filename + "</u> <br/>";
if (fileupload1.hasfile)
{
Try
{
Stream stream = fileupload1.filecontent;
StreamReader reader = new StreamReader (stream);
String strLine = "";
Todo
{
StrLine = reader. ReadLine ();
str = strLine;
while (strLine!= null);
}
catch (Exception ex)
{
str = "<br/> <b> Error </b> <br/> Unable to display" + Fileupload1.filename +
"<br/>" + ex. message;
}
}
Else
{
str = "No file uploaded."
}
Lbldisplay.text = str;
Lblmessage.text = "";
}
}
The highlighted using declaration is necessary to use a Stream object without a fully qualified namespace.

In the Btnsave_click event handler for the Save button, the HasFile property of the FileUpload control is used to detect whether a valid fully qualified file name is entered in the text box. If the text box is empty or the name entered is invalid, the detection will not pass, and lblmessage will display "No file upladed".

Assuming that a valid file is uploaded, the code in the try code block is executed. The key statement is the SaveAs method that invokes the File-upload control. This method uses the hard-coded path and the FileName property to pass a fully qualified file name. The statement may fail for a variety of reasons, including insufficient disk space, invalid paths, or security issues (later in more detail).

If the SaveAs method fails, a catch code block is executed. An error message is displayed in the Lblmessage, including the Messages property Ex.message of the exception.

If the SaveAs method succeeds, multiple information about the uploaded file is displayed in Lblmessage, which is obtained through the properties in Fileupload.postedfile (type Httppostedfile).

The Display button's Click event handler is similar to the previous, except that instead of displaying the file information, it displays the contents of the file. It obtains the contents of the upload file that behaves as a stream object by using the Filecontent property, and the stream object is used to instantiate a StreamReader object. The StreamReader Read-line method traverses the file line by row and then displays the merged string in Lbldisplay.

When discussing uploading files from a client to a Web server, security is a concern. Note that two points, first of all, the use of this method will expose the Web server, so there will be a very large security vulnerabilities, to be particularly careful. Because this can not only upload viruses, trojans and other malicious software, there will be a client browsing the Web server eye

The danger of recording the structure. Therefore, you should use a hard-coded target directory, at least to strictly limit where to save uploaded files.

Also, it is important to note that the permissions required to write files on the disk are allowed. When developing Web applications, the development machine is also a Web server in general, especially with the VS2005 default development pattern. In this mode, the built-in Web server is used, and the Web site is accessed by the file system instead of through IIS. This way, there will never be a problem with permissions.

However, problems can occur when a Web site is deployed to a product server, and the site is accessed through IIS and virtual directories. This is because the account that runs ASP.net must have write access to the directory where the uploaded files are saved. In Windows2000/xp, the name of the account is ASPNET. In Windows Server2003, write permissions must be assigned to the IIS_WPG account group.

Using the FileUpload control and combining good security protection, users can transfer their own files to the website to enrich the function of the website.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.