Recipe 15.2 Uploading a File to the Web Server

     

15.2.1 Problem

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

15.2.2 Solution

To enable a page to upload a file to the server, the form encoding type must be set to multipart/form-data and the form must include an input control with the type set to file and a button to initiate the upload process. When the user clicks the button, the code-behind can save the file to the filesystem.

In the .aspx file:

  1. Set the form encoding type to multipart/form-data .

  2. Add an HTML input control with the type set to file .

  3. 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 filename length and the content length to make sure they are not 0.

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

Example 15-4 shows the .aspx file for an application we've written to demonstrate this solution by allowing you to browse for a file and then 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 Example 15-5 (VB) and Example 15-6 (C#). The UI for uploading a file is shown in Figure 15-3.

Figure 15-3. UI for uploading a file
figs/ancb_1503.gif

15.2.3 Discussion

Uploading files to a web server is not a feature that most applications require. 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 then 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.

To enable an application to submit a form to a server with a file attached, you must set the encoding type of the Form element of the .aspx file to multipart/form-data , as shown in our example.

The .aspx file must also include an input element with its type set to file . 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. Their data will be submitted just 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, be sure to confirm that the file upload completed successfully. This can be done by checking the length, after trimming, of the filename of the uploaded file to make sure it is not 0 and checking the file's content length to make sure it is not 0. A production application should use validation controls to check these conditions and output an error message to the user. Refer to Chapter 2 for a discussion of validation controls.

After you verify that the file has been uploaded, it can be saved to the filesystem. The SaveAs method of the PostedFile object saves the uploaded file contents to a file on the web server. It requires a fully qualified filename on the web server. Unfortunately, the name of the file in the txtUpload.PostedFile object of our example is a fully qualified filename to the file on the client's machine. As shown in the example, we must extract the name of the file from the txtUpload.PostedFile and then build a fully qualified filename for the storage location and name on the web server.

By default, the ASPNET account under which ASP.NET runs does not have permission to write files to the filesystem of the server. You will need to modify the security settings on the folder used for uploads to allow the ASPNET user 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, select Properties, and then select the Security tab.

  3. Add the ASPNET user and allow write access.


By default, file uploads are limited to 4M. Any attempt to upload a file larger that 4M 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"             appRequestQueueLimit="100"/> 


15.2.4 See Also

Chapter 2 for validation examples

Example 15-4. File upload (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false"           Codebehind="CH15FileUploadVB.aspx.vb"           Inherits="ASPNetCookbook.VBExamples.CH15FileUploadVB" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title>File Upload</title>     <link rel="stylesheet" href="css/ASPNetCookbook.css">   </head>   <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0">  <form id="frmUpload" method="post" runat="server"   enctype="multipart/form-data">  <table width="100%" cellpadding="0" cellspacing="0" border="0">         <tr>           <td align="center">             <img src="images/ASPNETCookbookHeading_blue.gif">           </td>         </tr>         <tr>           <td class="dividerLine">             <img src="images/spacer.gif" height="6" border="0"></td>         </tr>       </table>       <table width="90%" align="center" border="0">         <tr>           <td align="center">&nbsp;</td>         </tr>         <tr>           <td align="center" class="PageHeading">             File Upload (VB)           </td>         </tr>         <tr>           <td><img src="images/spacer.gif" height="10" border="0"></td>         </tr>         <tr>           <td align="center">  <input id="txtUpload" runat="server" type="file" >  </td>         </tr>         <tr>           <td align="center">             <br />  <input id="btnUpload" runat="server"   type="button" value="Upload">  </td>         </tr>       </table>     </form>   </body> </html> 

Example 15-5. File upload code-behind (.vb)
 Option Explicit On  Option Strict On '----------------------------------------------------------------------------- ' '   Module Name: CH15FileUploadVB.aspx.vb ' '   Description: This module provides the code behind for the  '                CH15FileUploadVB.aspx page '***************************************************************************** Imports System Imports System.IO Imports System.Web.UI Namespace ASPNetCookbook.VBExamples   Public Class CH15FileUploadVB     Inherits System.Web.UI.Page     'controls on the form     Protected txtUpload As System.Web.UI.HtmlControls.HtmlInputFile     Protected WithEvents btnUpload As HtmlControls.HtmlInputButton     '*************************************************************************     '     '   ROUTINE: Page_Load     '     '   DESCRIPTION: This routine provides the event handler for the page load     '                event.  It is responsible for initializing the controls      '                on the page.     '-------------------------------------------------------------------------     Private Sub Page_Load(ByVal sender As System.Object, _                           ByVal e As System.EventArgs) Handles MyBase.Load       'Nothing is required for this example     End Sub  'Page_Load     '*************************************************************************     '     '   ROUTINE: btnUpload_ServerClick     '     '   DESCRIPTION: This routine provides the event handler for the upload     '                button click event.  It is responsible saving the file     '                to the local file system.     '-------------------------------------------------------------------------  Private Sub btnUpload_ServerClick(ByVal sender As Object, _   ByVal e As System.EventArgs) _   Handles btnUpload.ServerClick   Dim filename As String   Dim file As FileInfo   'make sure file was specified and was found   filename = txtUpload.PostedFile.FileName.Trim   If ((filename.Length > 0) And _   (txtUpload.PostedFile.ContentLength > 0)) Then   'get a fileInfo object to simplify extraction of the filename   'from the fully qualified filename   file = New FileInfo(filename)   'save the file to the local file system   txtUpload.PostedFile.SaveAs(Server.MapPath("uploads") & _   "\" & file.Name)   End If   End Sub  'btnUpload_ServerClick  End Class  'CH15FileUploadVB End Namespace 

Example 15-6. File upload code-behind (.cs)
 //---------------------------------------------------------------------------- // //   Module Name: CH15FileUploadCS.aspx.cs // //   Description: This module provides the code behind for the  //                CH15FileUploadCS.aspx page // //**************************************************************************** using System; using System.IO; namespace ASPNetCookbook.CSExamples {   public class CH15FileUploadCS : System.Web.UI.Page   {     // controls on the form     protected System.Web.UI.HtmlControls.HtmlInputFile txtUpload;     protected System.Web.UI.HtmlControls.HtmlInputButton btnUpload;     //************************************************************************     //     //   ROUTINE: Page_Load     //     //   DESCRIPTION: This routine provides the event handler for the page      //                load event.  It is responsible for initializing the      //                controls on the page.     //------------------------------------------------------------------------     private void Page_Load(object sender, System.EventArgs e)     {       // wire the upload button event handler       this.btnUpload.ServerClick +=          new EventHandler(this.btnUpload_ServerClick);     }  // Page_Load     //************************************************************************     //     //   ROUTINE: btnUpload_ServerClick     //     //   DESCRIPTION: This routine provides the event handler for the upload     //                button click event.  It is responsible saving the file     //                to the local file system.     //------------------------------------------------------------------------  private void btnUpload_ServerClick(object sender, System.EventArgs e)   {   string filename = null;   FileInfo file = null;   // make sure file was specified and was found   filename = txtUpload.PostedFile.FileName.Trim( );   if ((filename.Length > 0) &&   (txtUpload.PostedFile.ContentLength > 0))   {   // get a fileInfo object to simplify extraction of the filename   // from the fully qualified filename   file = new FileInfo(filename);   // save the file to the local file system   txtUpload.PostedFile.SaveAs(Server.MapPath("uploads") +   "\" + file.Name);   }   }  // btnUpload_ServerClick  }  // CH15FileUploadCS } 



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

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