Recipe 18.3. Uploading a File to the Web Server


Problem

You need to provide the ability for a user to upload a file to the web server filesystem.

Solution

Add to your page a FileUpload control and a button to initiate the upload process. When the user clicks the button, the code-behind can save the file to the filesystem.

Create a folder within your application file structure where the uploaded files will be placed, such as as one named uploads.

In the .aspx file:

  1. Add a FileUpload control.

  2. Add an Upload (or equivalently named) button.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Verify, in the Upload button click event handler, that the file content has been uploaded by checking the HasFile property of the FileUpload control.

  2. Save the file to the local filesystem on the server using the SaveAs method of the FileUpload object.

Example 18-4 shows the .aspx file for an application we've written to demonstrate this solution by allowing you to browse for a file and uploading the chosen file to your web server's local filesystem when you click the Upload button. The code-behind files for the application are shown in Examples 18-5 (VB) and 18-6 (C#). The UI for uploading a file is shown in Figure 18-3.

Figure 18-3. UI for uploading a file


Discussion

Most applications do not require uploading files to a web server. Nevertheless, here are a few examples of applications for which this capability comes in handy:


Departmental content management system

Uploading images or documents


Technical support site

Uploading error logs and defective documents or files


Graphics library

Allowing users to be able to make their own graphics file submissions

When uploading files is needed, the support provided by ASP.NET makes the implementation straightforward.

The application we've written to illustrate the solution allows you to browse for a file and upload the chosen file to your web server's local filesystem when you click the Upload button. For all that it accomplishes, the application requires a remarkably small amount of code.

The .aspx file must also include a FileUpload control. This causes the browser to render the input element with a Browse…button to allow the user to browse to the file to upload.

To give your user the ability to initiate the upload, you'll want to add an Upload button to your .aspx file. Your .aspx file can contain as many controls as you need to allow users to interact with the application, such as other input controls or dropdowns. The user's data will be submitted like any other form for use on the server side.

Place code to save the uploaded file to the server in the Upload button click event handler of the code-behind. Before saving the file, confirm that the file upload completed successfully. This can be done by checking the HasFile property of the FileUpload control to ensure it is set to true. A production application should use validation controls to check this condition and output an error message to the user. Refer to Chapter 3 for a discussion of validation controls.

After you verify the file has been uploaded, it can be saved to the filesystem. The SaveAs method of the FileUpload object saves the uploaded file contents to a file on the web server. It requires a fully qualified filename on the web server. As shown in the example, we get the name of the file from the FileName property of the FileUpload control and then build a fully qualified filename for the storage location and name on the web server.

By default, the account under which ASP.NET runs does not have permission to write files to the filesystem of the server. The account used varies with the server on which your application runs and depends on whether your application uses impersonation.

The name of the ASP.NET user can be determined by creating an ASP.NET page with the following content and displaying the page in a browser:

 <%@ Page Language="VB" %> <% Response.Write(System.Security.Principal.WindowsIdentity. GetCurrent().Name) %> <%@ Page Language="C#" %> <%Response.Write(System.Security.Principal.WindowsIdentity. GetCurrent().Name); %> 

You will need to modify the security settings on the folder used for uploads to allow the account used by ASP.NET to write to the folder. The steps for doing so vary somewhat for the different flavors of Windows, but the basic steps are these:

  1. Using Windows Explorer, browse to the folder where the uploaded files will be saved.

  2. Access the security settings by right-clicking on the folder, selecting Properties, and selecting the Security tab.

  3. Add the user account and allow write access.


By default, file uploads are limited to 4MB. Any attempt to upload a file larger than 4MB will result in an error message. The error message is generated by ASP.NET before any of your code runs; therefore, you have no control over the message being displayed.

You can change the maximum file size that can be uploaded by changing the maxRequestLength attribute of the httpRuntime element in the web.config file, as shown here (the value must be set in kilobytes):

 <httpRuntime executionTimeout="90" maxRequestLength="4096" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" requestLengthDiskThreshold="1024" appRequestQueueLimit="100"/> 


See Also

Chapter 3 for validation examples

Example 18-4. File upload (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH18FileUploadVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH18FileUploadVB" Title="File Upload" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > File Upload (VB) </div> <table width="90%" align="center" border="0"> <tr> <td align="center"> <asp:FileUpload  runat="server" /> </td> </tr> <tr> <td align="center"> <br /> <input  runat="server"   type="button"   value="Upload" onserverclick="btnUpload_ServerClick" /> </td> </tr> </table> </asp:Content> 

Example 18-5. File upload code-behind (.vb)

 Option Explicit On Option Strict On Imports System.IO Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code-behind for ''' CH18FileUploadVB.aspx ''' </summary> Partial Class CH18FileUploadVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the upload button click ''' event. It is responsible saving the file to the local filesystem. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnUpload_ServerClick(ByVal sender As Object, _              ByVal e As System.EventArgs) 'make sure file was specified and was found If (fuUpload.HasFile) Then fuUpload.SaveAs(Server.MapPath("uploads") & _ "\" & fuUpload.FileName) End If End Sub 'btnUpload_ServerClick End Class 'CH18FileUploadVB End Namespace 

Example 18-6. File upload code-behind (.cs)

 using System; using System.IO; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code-behind for /// CH18FileUploadCS.aspx /// </summary> public partial class CH18FileUploadCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the upload button click /// event. It is responsible saving the file to the local filesystem. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnUpload_ServerClick(Object sender,  System.EventArgs e) { // make sure file was specified and was found if (fuUpload.HasFile) { fuUpload.SaveAs(Server.MapPath("uploads") + "\\" + fuUpload.FileName); } } // btnUpload_ServerClick } // CH18FileUploadCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net