Microsoft.NET

……………………………………………….Expertise in .NET Technologies

FileUpload Server Control in ASP.NET

Posted by Ravi Varma Thumati on November 17, 2009

In ASP.NET 1.0/1.1, you could upload files using the HTML FileUpload server control. This control put an <input type=”file”> element on your Web page to enable the end user to upload files to the server. To use the file, however, you had to make a couple of modifications to the page. For example, you were required to add enctype=”multipart/form-data” to the pages <form> element.

ASP.NET 2.0 introduces a new FileUpload server control that makes the process of uploading files to a server even simpler. When giving a page the capability to upload files, you simply include the new <asp:FileUpload> control and ASP.NET takes care of the rest, including adding the enctype attribute to the page’s <form> element.

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.

Uploading Files Using the FileUpload Control

After the file is uploaded to the server, you can also take hold of the uploaded file’s properties and either display them to the end user or use these values yourself in your page’s code behind. Listing 1 shows an example of using the new FileUpload control. The page contains a single FileUpload control, plus a Button and a Label control.

Listing 1: Uploading files using the new FileUpload control

VB

<%@ Page%>
<script runat="server">
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If FileUpload1.HasFile Then
            Try
                FileUpload1.SaveAs("C:\Uploads\" & _
                   FileUpload1.FileName)
                Label1.Text = "File name: " & _
                   FileUpload1.PostedFile.FileName & "<br>" & _
                   "File Size: " & _
                   FileUpload1.PostedFile.ContentLength & " kb<br>" & _
                   "Content type: " & _
                   FileUpload1.PostedFile.ContentType
            Catch ex As Exception
                Label1.Text = "ERROR: " & ex.Message.ToString()
            End Try
        Else
            Label1.Text = "You have not specified a file."
        End If
   End Sub

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Server Control</title>
</head>
<body>
    <form runat="server">

        <asp:FileUpload runat="server" />
        <p>
        <asp:Button runat="server" Text="Upload"
         OnClick="Button1_Click" /></p>
        <p>
        <asp:Label runat="server"></asp:Label></p>

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

C#

<%@ Page%>
<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
           try {
              FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
              Label1.Text = "File name: " +
                   FileUpload1.PostedFile.FileName + "<br>" +
                   FileUpload1.PostedFile.ContentLength + " kb<br>" +
                   "Content type: " +
                   FileUpload1.PostedFile.ContentType;
           }
            catch (Exception ex) {
              Label1.Text = "ERROR: " + ex.Message.ToString();
            }
        else
        {
           Label1.Text = "You have not specified a file.";
        }
    }

</script>

From this example, you can see that the entire process is rather simple. The single button on the page initiates the upload process. The FileUpload control itself does not initiate the uploading process. You must initiate it through another event such as Button_Click.

When compiling and running this page, you may notice a few things in the generated source code of the page. An example of the generated source code is presented here:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
      FileUpload Server Control
</title></head>

<body>
    <form method="post" action="FileUpload.aspx"
     enctype="multipart/form-data">
<div>
<input
 value="/wEPDwUKMTI3ODM5MzQ0Mg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm
 0tZGF0YWRkrSpgAFaEKed5+5/8+zKglFfVLCE=" />
</div>
   <input />
   <p>

   <input value="Upload" /></p>
   <p>
   <span></span></p>

<div>
<input
 value="/wEWAgL1wLWICAKM54rGBqfR8MhZIDWVowox+TUvybG5Xj0y" />

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

The first thing to notice is that because the FileUpload control is on the page, ASP.NET 2.0 modified the page’s <form> element on your behalf by adding the appropriate enctype attribute. Also notice that the FileUpload control was converted to an HTML <input> element.

After the file is uploaded, the first check (done in the file’s Button1_Click event handler) examines whether a file reference was actually placed within the <input type="file"> element. If a file was specified, an attempt is made to upload the referenced file to the server using the SaveAs method of the FileUpload control. That method takes a single String parameter, which should include the location where you want to save the file. In the String parameter used in Listing 1, you can see that the file is being saved to a folder called Uploads, which is located in the C:\ drive.

The PostedFile.FileName attribute is used to give the saved file the same name as the file it was copied from. If you want to name the file something else, simply use the SaveAs method in the following manner:

FileUpload1.SaveAs("C:\Uploads\UploadedFile.txt")

You could also give the file a name that specifies the time it was uploaded:

FileUpload1.SaveAs("C:\Uploads\" &
   System.DateTime.Now.ToFileTimeUtc() & ".txt")

After the upload is successfully completed, the Label control on the page is populated with metadata of the uploaded file. In the example, the file’s name, size, and content type are retrieved and displayed on the page for the end user. When the file is uploaded to the server, the page generated is similar to that shown in Figure 1.

Figure 1

Uploading files to another server can be an error-prone affair. It is vital to upload files in your code using proper exception handling. That’s why the file in the example is uploaded using a Try Catch statement.

Giving ASP.NET Proper Permissions to Upload Files

You might receive errors when your end users upload files to your Web server through the FileUpload control in your application. These might occur because the destination folder on the server is not writable for the account used by ASP.NET. If ASP.NET is not enabled to write to the folder you want, you can enable it using the folder’s properties.

First, right-click on the folder where the ASP.NET files should be uploaded and select Properties from the provided menu. The Properties dialog for the selected folder opens. Click the Security tab to make sure the ASP.NET Machine Account is included in the list and has the proper permissions to write to disk. If it is enabled, you see something similar to what is presented in Figure 2.


Figure 2

If you don’t see the ASP.NET Machine Account in the list of users allowed to access the folder, add ASP.NET by clicking the Add button and entering ASPNET (without the period) in the text area provided (see Figure 3).

Figure 3

Click OK, and you can then click the appropriate check boxes to provide the permissions needed for your application.

Understanding File Size Limitations

Your end users might never encounter an issue with the file upload process in your application, but you should be aware that some limitations exist. When users work through the process of uploading files, a size restriction is actually sent to the server for uploading. The default size limitation is 4MB (4096kb); the transfer fails if a user tries to upload a file that is larger than 4096kb.

A size restriction protects your application. You want to prevent malicious users from uploading numerous large files to your Web server in an attempt to tie up all the available processes on the server. Such an occurrence is called a denial of service attack. It ties up the Web server’s resources so that legitimate users are denied responses from the server.

One of the great things about .NET, however, is that it usually provides a way around limitations. You can usually change the default settings that are in place. To change the limit on the allowable upload file size, you make some changes in either the web.config.comments (found in the ASP.NET 2.0 configuration folder at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG) or in your application’s web.config file.

In the web.config.comments file, find a node called <httpRuntime>. In this file, you see that the default allowable file size is dictated by the actual request size permitted to the Web server (4096KB). The <httpRuntime> section of the web.config.comments file is shown in Listing 2.

Listing 2: Changing the file-size limitation setting in the web.config file

<httpRuntime
 executionTimeout="110"
 maxRequestLength="4096"
 requestLengthDiskThreshold="80"
 useFullyQualifiedRedirectUrl="false"
 minFreeThreads="8"
 minLocalRequestFreeThreads="4"
 appRequestQueueLimit="5000"
 enableKernelOutputCache="true"
 enableVersionHeader="true"
 requireRootedSaveAsPath="true"
 enable="true"
 shutdownTimeout="90"
 delayNotificationTimeout="5"
 waitChangeNotification="0"
 maxWaitChangeNotification="0"
 enableHeaderChecking="true"
 sendCacheControlHeader="true"
 apartmentThreading="false" />

You can do a lot with the <httpRuntime> section of the web.config file, but two properties — the maxRequestLength and executionTimeout properties — are especially interesting.

The maxRequestLength property is the setting that dictates the size of the request made to the Web server. When you upload files, the file is included in the request; you alter the size allowed to be uploaded by changing the value of this property. The value presented is in kilobytes. To allow files larger than the default of 4MB, change the maxRequestLength property as in the following:

maxRequestLength="11000"

This example changes the maxRequestLength property’s value to 11,000KB (around 10MB). With this setting in place, your end users can upload 10MB files to the server. When changing the maxRequestLength property, be aware of the setting provided for the executionTimeout property. This property sets the time (in seconds) for a request to attempt to execute to the server before ASP.NET shuts down the request (whether or not it is finished). The default setting is 90 seconds. The end user receives a timeout error notification in the browser if the time limit is exceeded. If you are going to permit larger requests, remember that they take longer to execute than smaller ones. If you increase the size of the maxRequestLength property, you should examine whether to increase the executionTimeout property as well.

If you are working with smaller files, it’s advisable to reduce the size allotted for the request to the Web server by decreasing the value of the maxRequestLength property. This helps safeguard your application from a denial of service attack.

Making these changes in the web.config.comments file applies this setting to all the applications that are on the server. If you want to apply this only to the application you are working with, apply the <httpRuntime> node to the web.config file of your application, overriding any setting that is in the web.config.comments file. Make sure this node resides between the <system.web> nodes in the configuration file.

Uploading Multiple Files from the Same Page

So far, you have seen some good examples of how to upload a file to the server without much hassle. Now, take a look at how to upload multiple files to the server from a single page.

No built-in capabilities in the Microsoft .NET Framework enable you to upload multiple files from a single ASP.NET page. With a little work, however, you can easily accomplish this task just as you would have in the past using .NET 1.x.

The trick is to import the System.IO class into your ASP.NET page and then to use the HttpFileCollection class to capture all the files that are sent in with the Request object. This approach enables you to upload as many files as you want from a single page.

If you wanted to, you could simply handle each and every FileUpload control on the page individually as shown in in Listing 3.

Listing 3: Handling each FileUpload control individually

VB

If FileUpload1.HasFile Then

‘ Handle file

End If

If FileUpload2.HasFile Then

‘ Handle file

End If

C#

if (FileUpload1.HasFile) {

// Handle file

}

if (FileUpload2.HasFile) {

// Handle file

}

If you are working with a limited number of file upload boxes, this approach works; but at the same time you may, in certain cases, want to handle the files using the HttpFileCollection class. This is especially true if you are working with a dynamically generated list of server controls on your ASP.NET page.

For an example of this, you can build an ASP.NET page that has three FileUpload controls and one Submit button (using the Button control). After the user clicks the Submit button and the files are posted to the server, the code behind takes the files and saves them to a specific location on the server. After the files are saved, the file information that was posted is displayed in the ASP.NET page (see Listing 4).

Listing 4: Uploading multiple files to the server

VB

Protected Sub Button1_Click(ByVal sender As Object, _

ByVal e As System.EventArgs)

Dim filepath As String = “C:\Uploads”

Dim uploadedFiles As HttpFileCollection = Request.Files

Dim i As Integer = 0

Do Until i = uploadedFiles.Count

Dim userPostedFile As HttpPostedFile = uploadedFiles(i)

Try

If (userPostedFile.ContentLength > 0) Then

Label1.Text += “<u>File #” & (i + 1) & “</u><br>”

Label1.Text += “File Content Type: ” & _

userPostedFile.ContentType & “<br>”

Label1.Text += “File Size: ” & _

userPostedFile.ContentLength & “kb<br>”

Label1.Text += “File Name: ” & _

userPostedFile.FileName & “<br>”

userPostedFile.SaveAs(filepath & “\” & _

System.IO.Path.GetFileName(userPostedFile.FileName))

Label1.Text += “Location where saved: ” & _

filepath & “\” & _

System.IO.Path.GetFileName(userPostedFile.FileName) & _

“<p>”

End If

Catch ex As Exception

Label1.Text += “Error:<br>” & ex.Message

End Try

i += 1

Loop

End Sub

C#

protected void Button1_Click(object sender, EventArgs e)

{

string filepath = “C:\\Uploads”;

HttpFileCollection uploadedFiles = Request.Files;

for (int i = 0; i < uploadedFiles.Count; i++)

{

HttpPostedFile userPostedFile = uploadedFiles[i];

try

{

if (userPostedFile.ContentLength > 0 )

{

Label1.Text += “<u>File #” + (i+1) +

“</u><br>”;

Label1.Text += “File Content Type: ” +

userPostedFile.ContentType + “<br>”;

Label1.Text += “File Size: ” +

userPostedFile.ContentLength + “kb<br>”;

Label1.Text += “File Name: ” +

userPostedFile.FileName + “<br>”;

userPostedFile.SaveAs(filepath + “\\” +

System.IO.Path.GetFileName(userPostedFile.FileName));

Label1.Text += “Location where saved: ” +

filepath + “\\” +

System.IO.Path.GetFileName(userPostedFile.FileName) +

“<p>”;

}

}

catch (Exception Ex)

{

Label1.Text += “Error: <br>” + Ex.Message;

}

}

}

This ASP.NET page enables the end user to select up to three files and click the Upload Files button, which initializes the Button1_Click event. Using the HttpFileCollection class with the Request.Files property lets you gain control over all the files that are uploaded from the page. When the files are in this state, you can do whatever you want with them. In this case, the files’ properties are examined and written to the screen. In the end, the files are saved to the Uploads folder in the root directory of the server. The result of this action is illustrated in Figure 4.

Examples

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.

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.

Visual Basic

<%@ Page Language=”VB” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<script runat=”server”>

Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)

‘ Specify the path on the server to

‘ save the uploaded file to.

Dim savePath As String = “c:\temp\uploads\”

‘ Before attempting to perform operations

‘ on the file, verify that the FileUpload

‘ control contains a file.

If (FileUpload1.HasFile) Then

‘ Get the name of the file to upload.

Dim fileName As String = 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 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.”

End If

End Sub

</script>

<html  >

<head runat=”server”>

<title>FileUpload 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>

C#

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<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  >

<head runat=”server”>

<title>FileUpload 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>

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.

Visual Basic

<%@ Page Language=”VB” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<script runat=”server”>

Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)

‘ 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

‘ files in a separate directory. This helps prevent

‘ users from overwriting existing application files by

‘ uploading files with names like “Web.config”.

Dim saveDir As String = “\Uploads\”

‘ Get the physical file system path for the currently

‘ executing application.

Dim appPath As String = Request.PhysicalApplicationPath

‘ Before attempting to save the file, verify

‘ that the FileUpload control contains a file.

If (FileUpload1.HasFile) Then

Dim savePath As String = 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.”

End If

End Sub

</script>

<html  >

<head runat=”server”>

<title>FileUpload Class Example</title>

</head>

<body>

<h3>FileUpload Class Example: Save To Application 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>

C#

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<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

// 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  >

<head runat=”server”>

<title>FileUpload Class Example</title>

</head>

<body>

<h3>FileUpload Class Example: Save To Application 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>

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.

Visual Basic

<%@ Page Language=”VB” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<script runat=”server”>

Protected Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)

‘ Specify the path on the server to

‘ save the uploaded file to.

Dim savePath As String = “c:\temp\uploads\”

‘ Before attempting to save the file, verify

‘ that the FileUpload control contains a file.

If (FileUpload1.HasFile) Then

‘ Get the size in bytes of the file to upload.

Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength

‘ Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.

If (fileSize < 2100000) Then

‘ 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.”

End If

Else

‘ Notify the user that a file was not uploaded.

UploadStatusLabel.Text = “You did not specify a file to upload.”

End If

End Sub

</script>

<html  >

<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>

C#

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<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 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>

<html  >

<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>

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.

Visual Basic

<%@ Page Language=”VB” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<script runat=”server”>

Protected Sub UploadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)

‘ Specify the path on the server to

‘ save the uploaded file to.

Dim savePath As String = “c:\temp\uploads\”

‘ Before attempting to save the file, verify

‘ that the FileUpload control contains a file.

If (FileUpload1.HasFile) Then

‘ Get the name of the file to upload.

Dim fileName As String = Server.HtmlEncode(FileUpload1.FileName)

‘ Get the extension of the uploaded file.

Dim extension As String = System.IO.Path.GetExtension(fileName)

‘ Allow only files with .doc or .xls extensions

‘ to be uploaded.

If (extension = “.doc”) Or (extension = “.xls”) Then

‘ 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.”

End If

Else

‘ Notify the user that a file was not uploaded.

UploadStatusLabel.Text = “You did not specify a file to upload.”

End If

End Sub

</script>

<html  >

<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>

C#

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<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”;

// 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.”;

}

}

}

</script>

<html  >

<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>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: