file upload class web controls)

14
Home Library Learn Downloads Support Syntax Remarks More... MSDN Library .NET Development .NET Framework 4 .NET Framework Class Library System.Web.UI.WebControls Namespace FileUpload Class FileUpload Members FileUpload Constructor FileUpload Methods FileUpload Properties FileUpload Events Community Content Add code samples and tips to enhance this topic. Sign in | United States - English | Preferences .NET Framework Class Library FileUpload Class Displays a text box control and a browse button that enable users to select a file to upload to the server. Namespace: System.Web.UI.WebControls Assembly: System.Web (in System.Web.dll) In this topic: Saving Uploaded Files Security Considerations Memory Limitations Using the FileUpload Control with the UpdatePanel Control Declarative Syntax Introduction The FileUpload class displays a text box control and a browse button that enable users to select a file on the client and upload it to the Web server. The user specifies the file to upload by entering the full path of the file on the local computer (for example, C:\MyFiles\TestFile.txt) in the text box of the control. Alternately, the user can select the file by clicking the Browse button, and then locating it in the Choose File dialog box. Use the FileName property to get the name of a file on a client to upload by using the FileUpload control. The file name that this property returns does not include the path of the file on the client. The FileContent property gets a Stream object that points to a file [ValidationPropertyAttribute("FileName")] [ControlValuePropertyAttribute("FileBytes")] public class FileUpload : WebControl Copy <asp:FileUpload /> Copy VB C# C++ F# JScript 4/28/2010 FileUpload Class (System.Web.UI.WebC… …microsoft.com/…/system.web.ui.webco… 1/14

Upload: ghostx

Post on 08-Apr-2015

39 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: File Upload Class Web Controls)

Home Library Learn Downloads Support

Syntax

Remarks

More...

MSDN Library

.NET Development

.NET Framework 4

.NET Framework Class Library

System.Web.UI.WebControls Namespace

FileUpload Class

FileUpload Members

FileUpload Constructor

FileUpload Methods

FileUpload Properties

FileUpload Events

Community Content

Add code samples and tips to

enhance this topic.

Sign in | United States - English | Preferences

.NET Framework Class Library

FileUpload Class

Displays a text box control and a browse button that enable users

to select a file to upload to the server.

Namespace: System.Web.UI.WebControls

Assembly: System.Web (in System.Web.dll)

In this topic:

Saving Uploaded Files

Security Considerations

Memory Limitations

Using the FileUpload Control with the UpdatePanel Control

Declarative Syntax

Introduction

The FileUpload class displays a text box control and a browse

button that enable users to select a file on the client and upload it

to the Web server. The user specifies the file to upload by

entering the full path of the file on the local computer (for

example, C:\MyFiles\TestFile.txt) in the text box of the control.

Alternately, the user can select the file by clicking the Browse

button, and then locating it in the Choose File dialog box.

Use the FileName property to get the name of a file on a client to

upload by using the FileUpload control. The file name that this

property returns does not include the path of the file on the client.

The FileContent property gets a Stream object that points to a file

[ValidationPropertyAttribute("FileName")][ControlValuePropertyAttribute("FileBytes")]public class FileUpload : WebControl

Copy

<asp:FileUpload />Copy

VB C# C++ F# JScript

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 1/14

Page 2: File Upload Class Web Controls)

to upload. Use this property to access the contents of the file as

bytes. For example, you can use the Stream object that is returned

by the FileContent property to read the contents of the file as

bytes and store them in a byte array. Alternatively, you can use the

FileBytes property to retrieve all the bytes in the file.

The PostedFile property gets the underlying HttpPostedFile object

for the file to upload. You can use this property to access

additional properties on the file. The ContentLength property gets

the length of the file. The ContentType property gets the MIME

content type of the file. In addition, you can use the PostedFile

property to access the FileName property, the InputStream

property, and the SaveAs method. However, the same functionality

is provided by the FileName property, the FileContent property,

and the SaveAs method.

Saving Uploaded Files

The FileUpload control does not automatically save a file to the

server after the user selects the file to upload. You must explicitly

provide a control or mechanism to allow the user to submit the

specified file. For example, you can provide a button that the user

clicks to upload the file. The code that you write to save the

specified file should call the SaveAs method, which saves the

contents of a file to a specified path on the server. Typically, the

SaveAs method is called in an event-handling method for an event

that raises a post back to the server. For example, if you provide

a button to submit a file, you could include the code to save the

file inside the event-handling method for the click event.

Before calling the SaveAs method to save the file to the server,

use the HasFile property to verify that the FileUpload control

contains a file. If the HasFile returns true, call the SaveAs method.

If it returns false, display a message to the user indicating that the

control does not contain a file. Do not check the PostedFile

property to determine whether a file to upload exists because, by

default, this property contains 0 bytes. As a result, even when the

FileUpload control is blank, the PostedFile property returns a non-

null value.

Security Considerations

When you call the SaveAs method, you must specify the full path

of the directory in which to save the uploaded file. If you do not

explicitly specify a path in your application code, an exception is

thrown when a user attempts to upload a file. This behavior helps

keep the files on the server secure by preventing users from

being able to write to arbitrary locations in your application's

directory structure, as well as preventing access to sensitive root

directories.

The SaveAs method writes the uploaded file to the specified

directory. Therefore, the ASP.NET application must have write

access to the directory on the server. There are two ways that the

application can get write access. You can explicitly grant write

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 2/14

Page 3: File Upload Class Web Controls)

access to the account under which the application is running, in

the directory in which the uploaded files will be saved.

Alternatively, you can increase the level of trust that is granted to

the ASP.NET application. To get write access to the executing

directory for the application, the application must be granted the

AspNetHostingPermission object with the trust level set to the

AspNetHostingPermissionLevel.Medium value. Increasing the level

of trust increases the application's access to resources on the

server. Note that this is not a secure approach, because a

malicious user who gains control of your application will also be

able to run under this higher level of trust. It is a best practice to

run an ASP.NET application in the context of a user with the

minimum privileges that are required for the application to run.

For more information about security in ASP.NET applications, see

Basic Security Practices for Web Applications and ASP.NET Trust

Levels and Policy Files.

Memory Limitations

One way to guard against denial of service attacks is to limit the

size of the files that can be uploaded by using the FileUpload

control. You should set a size limit that is appropriate for the

types of files that you expect to be uploaded. The default size

limit is 4096 kilobytes (KB), or 4 megabytes (MB). You can allow

larger files to be uploaded by setting the maxRequestLength

attribute of the httpRuntime element. To increase the maximum

allowable file size for the entire application, set the

maxRequestLength attribute in the Web.config file. To increase the

maximum allowable file size for a specified page, set the

maxRequestLength attribute inside the location element in

Web.config. For an example, see location Element (ASP.NET

Settings Schema).

When uploading large files, a user might also receive the

following error message:

aspnet_wp.exe (PID: 1520) was recycled because memory

consumption exceeded 460 MB (60 percent of available RAM).

If your users encounter this error message, increase the value of

the memoryLimit attribute in the processModel of element the

Web.config file for the application. The memoryLimit attribute

specifies the maximum amount of memory that a worker process

can use. If the worker process exceeds the memoryLimit amount,

a new process is created to replace it, and all current requests are

reassigned to the new process.

To control whether the file to upload is temporarily stored in

memory or on the server while the request is being processed,

set the requestLengthDiskThreshold attribute of the httpRuntime

element. This attribute enables you to manage the size of the

input stream buffer. The default is 256 bytes. The value that you

specify should not exceed the value that you specify for the

maxRequestLength attribute.

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 3/14

Page 4: File Upload Class Web Controls)

Using the FileUpload Control with the UpdatePanel

Control

The FileUpload control is designed to be used only in postback

scenarios and not in asynchronous postback scenarios during

partial-page rendering. When you use a FileUpload control inside

an UpdatePanel control, the file must be uploaded by using a

control that is a PostBackTrigger object for the panel.

UpdatePanel controls are used to update selected regions of a

page instead of updating the whole page with a postback. For

more information, see UpdatePanel Control Overview and Partial-

Page Rendering Overview.

Declarative Syntax

Topic Location

How to: Upload Files with the Building ASP .NET Web

<asp:FileUpload AccessKey="string" BackColor="color name|#dddddd" BorderColor="color name|#dddddd" BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge| Inset|Outset" BorderWidth="size" CssClass="string" Enabled="True|False" EnableTheming="True|False" EnableViewState="True|False" Font-Bold="True|False" Font-Italic="True|False" Font-Names="string" Font-Overline="True|False" Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium| Large|X-Large|XX-Large" Font-Strikeout="True|False" Font-Underline="True|False" ForeColor="color name|#dddddd" Height="size" ID="string" OnDataBinding="DataBinding event handler" OnDisposed="Disposed event handler" OnInit="Init event handler" OnLoad="Load event handler" OnPreRender="PreRender event handler" OnUnload="Unload event handler" runat="server" SkinID="string" Style="string" TabIndex="integer" ToolTip="string" Visible="True|False" Width="size"/>

Copy

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 4/14

Page 5: File Upload Class Web Controls)

Examples

FileUpload Web Server Control Applications

How to: Upload Files with the

FileUpload Web Server Control

Building ASP .NET Web

Applications

How to: Upload Files with the

FileUpload Web Server Control

Building ASP .NET Web

Applications in Visual Studio

How to: Set Focus on ASP.NET

Web Server Controls

Building ASP .NET Web

Applications

How to: Set Focus on ASP.NET

Web Server Controls

Building ASP .NET Web

Applications

How to: Set Focus on ASP.NET

Web Server Controls

Building ASP .NET Web

Applications in Visual Studio

How to: Upload Files with the

FileUpload Web Server Control

Building ASP .NET Web

Applications in Visual Studio

How to: Set Focus on ASP.NET

Web Server Controls

Building ASP .NET Web

Applications in Visual Studio

This section contains the following four examples:

The first example demonstrates how to create a FileUpload

control that saves files to a path that is specified in code.

The second example demonstrates how to create a

FileUpload control that saves files to a specified directory

in the file system for the application.

The third example demonstrates how to create a

FileUpload control that saves files to a specified path and

limits the size of the file that can be uploaded.

The fourth example demonstrates how to create a

FileUpload control that saves files to a specified path and

allows only files that have the .doc or .xls file name

extensions to be uploaded.

Caution

These examples demonstrate the basic syntax for the

FileUpload control, but they do not demonstrate all the

necessary error checking that should be completed before to

saving the file. For a more complete example, see SaveAs.

The following example demonstrates how to create a FileUpload

control that saves files to a path that is specified in code. The

SaveAs method is called to save the file to the specified path on

the server.

CopyVB C# C++ F# JScript

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 5/14

Page 6: File Upload Class Web Controls)

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void UploadButton_Click(object sender, EventArgs e) { // Specify the path on the server to // save the uploaded file to. String savePath = @"c:\temp\uploads\";

// Before attempting to perform operations // on the file, verify that the FileUpload // control contains a file. if (FileUpload1.HasFile) { // Get the name of the file to upload. String fileName = FileUpload1.FileName;

// Append the name of the file to upload to the path. savePath += fileName;

// Call the SaveAs method to save the // uploaded file to the specified path. // This example does not perform all // the necessary error checking. // If a file with the same name // already exists in the specified path, // the uploaded file overwrites it. FileUpload1.SaveAs(savePath);

// Notify the user of the name of the file // was saved under. UploadStatusLabel.Text = "Your file was saved as " + fileName; } else { // Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload."; }

}</script>

<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>FileUpload Example</title></head>

Copy4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 6/14

Page 7: File Upload Class Web Controls)

The following example demonstrates how to create a FileUpload

control that saves files to a specified directory in the file system

for the application. The HttpRequest.PhysicalApplicationPath

property is used to get the physical file system path of the root

directory for the currently executing server application. The

SaveAs method is called to save the file to the specified path on

the server.

<body> <form id="form1" runat="server"> <div> <h4>Select a file to upload:</h4>

<asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>

<br /><br />

<asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"> </asp:Button>

<hr />

<asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </div> </form></body></html>

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void UploadButton_Click(object sender, EventArgs e) { // Save the uploaded file to an "Uploads" directory // that already exists in the file system of the // currently executing ASP.NET application. // Creating an "Uploads" directory isolates uploaded

CopyVB C# C++ F# JScript

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 7/14

Page 8: File Upload Class Web Controls)

// files in a separate directory. This helps prevent // users from overwriting existing application files by // uploading files with names like "Web.config". string saveDir = @"\Uploads\";

// Get the physical file system path for the currently // executing application. string appPath = Request.PhysicalApplicationPath;

// Before attempting to save the file, verify // that the FileUpload control contains a file. if (FileUpload1.HasFile) { string savePath = appPath + saveDir + Server.HtmlEncode(FileUpload1.FileName);

// Call the SaveAs method to save the // uploaded file to the specified path. // This example does not perform all // the necessary error checking. // If a file with the same name // already exists in the specified path, // the uploaded file overwrites it. FileUpload1.SaveAs(savePath);

// Notify the user that the file was uploaded successfully. UploadStatusLabel.Text = "Your file was uploaded successfully.";

} else { // Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload."; } }</script>

<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>FileUpload Class Example</title></head><body> <h3>FileUpload Class Example: Save To Appli

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 8/14

Page 9: File Upload Class Web Controls)

The following example demonstrates how to create a FileUpload

control that saves files to a path that is specified in the code. The

control limits the size of the file that can be uploaded to 5 MB.

The PostedFile property is used to access the underlying

ContentLength property and return the size of the file. If the size

of the file to upload is less than 2 MB, the SaveAs method is

called to save the file to the specified path on the server. In

addition to checking for the maximum file size setting in your

application code, you can set the maxRequestLength attribute of

the httpRuntime element to a maximum allowable size in the

configuration file for your application.

cation Directory</h3> <form id="form1" runat="server"> <div> <h4>Select a file to upload:</h4>

<asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>

<br/><br/>

<asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"> </asp:Button>

<hr />

<asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </div> </form></body></html>

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void UploadButton_Click(object sender, EventArgs e) { // Specify the path on the server to // save the uploaded file to. string savePath = @"c:\temp\uploads\";

CopyVB C# C++ F# JScript

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 9/14

Page 10: File Upload Class Web Controls)

// Before attempting to save the file, verify // that the FileUpload control contains a file. if (FileUpload1.HasFile) { // Get the size in bytes of the file to upload. int fileSize = FileUpload1.PostedFile.ContentLength;

// Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded. if (fileSize < 2100000) {

// Append the name of the uploaded file to the path. savePath += Server.HtmlEncode(FileUpload1.FileName);

// Call the SaveAs method to save the // uploaded file to the specified path. // This example does not perform all // the necessary error checking. // If a file with the same name // already exists in the specified path, // the uploaded file overwrites it. FileUpload1.SaveAs(savePath);

// Notify the user that the file was uploaded successfully. UploadStatusLabel.Text = "Your file was uploaded successfully."; } else { // Notify the user why their file was not uploaded. UploadStatusLabel.Text = "Your file was not uploaded because " + "it exceeds the 2 MB size limit."; } } else { // Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload."; } }</script>

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 10/14

Page 11: File Upload Class Web Controls)

The following example demonstrates how to create a FileUpload

control that saves files to a path that is specified in the code. This

example allows only files that have the .doc or .xls file name

extensions to be uploaded. The Path.GetExtension method is

called to return the extension of the file to upload. If the file has a

.doc or .xls file name extension, the SaveAs method is called to

save the file to the specified path on the server.

<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>FileUpload Class Example</title></head><body> <form id="form1" runat="server"> <div> <h4>Select a file to upload:</h4>

<asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>

<br/><br/>

<asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"> </asp:Button>

<hr />

<asp:Label id="UploadStatusLabel" runat="server"> </asp:Label>

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

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void UploadBtn_Click(object sender, EventArgs e) { // Specify the path on the server to // save the uploaded file to. string savePath = @"c:\temp\uploads";

CopyVB C# C++ F# JScript

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 11/14

Page 12: File Upload Class Web Controls)

// Before attempting to save the file, verify // that the FileUpload control contains a file. if (FileUpload1.HasFile) { // Get the name of the file to upload. string fileName = Server.HtmlEncode(FileUpload1.FileName);

// Get the extension of the uploaded file. string extension = System.IO.Path.GetExtension(fileName);

// Allow only files with .doc or .xls extensions // to be uploaded. if ((extension == ".doc") || (extension == ".xls")) { // Append the name of the file to upload to the path. savePath += fileName;

// Call the SaveAs method to save the // uploaded file to the specified path. // This example does not perform all // the necessary error checking. // If a file with the same name // already exists in the specified path, // the uploaded file overwrites it. FileUpload1.SaveAs(savePath);

// Notify the user that their file was successfully uploaded. UploadStatusLabel.Text = "Your file was uploaded successfully."; } else { // Notify the user why their file was not uploaded. UploadStatusLabel.Text = "Your file was not uploaded because " + "it does not have a .doc or .xls extension."; }

}

}

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 12/14

Page 13: File Upload Class Web Controls)

Inheritance Hierarchy

Thread Safety

Platforms

System.Object

System.Web.UI.Control

System.Web.UI.WebControls.WebControl

System.Web.UI.WebControls.FileUpload

Any public static (Shared in Visual Basic) members of this type are

thread safe. Any instance members are not guaranteed to be

thread safe.

Windows 7, Windows Vista, Windows XP SP3, Windows XP Media

Center Edition, Windows XP Professional x64 Edition, Windows XP

Starter Edition, Windows Server 2008, Windows Server 2003,

Windows Server 2000 SP4, Windows Millennium Edition, Windows

98

</script>

<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>FileUpload Class Example</title></head><body> <form id="form1" runat="server"> <div> <h4>Select a file to upload:</h4>

<asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>

<br/><br/>

<asp:Button id="UploadBtn" Text="Upload file" OnClick="UploadBtn_Click" runat="server"> </asp:Button>

<hr />

<asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </div> </form></body></html>

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 13/14

Page 14: File Upload Class Web Controls)

Version Information

See Also

Community Content

© 2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Feedback

The .NET Framework and .NET Compact Framework do not

support all versions of every platform. For a list of the supported

versions, see http://msdn.microsoft.com/en-

us/library/8z6watww.aspx.

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

Reference

FileUpload Members

System.Web.UI.WebControls Namespace

SaveAs

4/28/2010 FileUpload Class (System.Web.UI.WebC…

…microsoft.com/…/system.web.ui.webco… 14/14