Recipe 18.4. Processing an Uploaded File Without Storing It on the Filesystem


Problem

You want a user to be able to upload a file to the web server for immediate processing without having to first store the file.

Solution

Implement the solution described in Recipe 18.2. Instead of writing the file to the filesystem, use the input stream containing the uploaded file to process the data.

For the .aspx file, follow the steps for implementing the .aspx file in Recipe 18.2 and then, if you like, add a control that will show the results of the processingfor example, a GridView control to display the contents of an uploaded XML file.

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

  1. Verify, in the Upload button click event handler, that the file has been uploadedthat is, that the HasFile property of the FileUpload control is set to TRueand (if appropriate) that it is a valid XML file.

  2. Load the updated data and, if you elected to include a control for showing the contents of the uploaded file, bind the uploaded data to the controlfor example, a GridView control.

Examples 18-8, 18-9 through 18-10 show the .aspx file and VB and C# code-behind files for an application we've written to illustrate this solution. The initial output is identical to Recipe 18.2's example output and is shown in Figure 18-3.

Discussion

This recipe demonstrates the concept of uploading files and processing them without having to store them to the local filesystem, as you might do with the contents of an XML file for example. This eliminates the problems of files being uploaded with the same names, inadvertently filling the hard drive, and the security aspects of allowing the ASP.NET write privileges on the local filesystem.

The example we've written to illustrate this solution is similar to the one described in Recipe 18.2, except that instead of saving the file contents to the filesystem, we process it immediately by loading the uploaded data into a DataSet and binding the DataSet to a GridView. What's more, our example uses the basic .aspx file described in Recipe 18.2 with a few changes to support using the page for uploading an XML file and displaying its contents.

In the Page_Load method of the code-behind, the table containing the upload controls is made visible and the GridView invisible. (We'll switch the visibility of the two at a later stage to display the contents of the processed file.)

When the user clicks the Upload button, the btnUpload_ServerClick method is executed. The code for ensuring a file was uploaded is identical to our example code in Recipe 18.2, except that, because this example is expecting XML data, an additional check is added to ensure the uploaded file is an XML file. Since the same page is used to display the contents of the uploaded file, the table containing the upload controls needs to be made invisible and the GridView used to display the contents of the uploaded file made visible.

Next, we use the File Content property of the FileUpload control to get the file content to load the data into the DataSet. In our example, the XML file shown in Example 18-7 is being uploaded and, because of its formatting, can be read directly into the DataSet. With other types of data, you may need to do other processing. In addition, production code should validate the content type of the posted file and the contents of the file to ensure the uploaded file is valid.

The last step in our example is to bind the GridView on the form to the DataSet containing the uploaded XML data. Figure 18-4 shows the output for the uploaded and processed file. For more information on data binding, refer to the recipes in Chapter 2.

Figure 18-4. Uploaded and processed file output


See Also

Chapter 3 for validation controls; FileUpload class documentation in the MSDN library for more information on file uploads

Example 18-7. uploaded XML file

 <Root> <Book> <BookID>1</BookID> <Title>Access Cookbook</Title> <ISBN>0-596-00084-7</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>2</BookID> <Title>ASP.NET Cookbook</Title> <ISBN>0-596-00378-1</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>3</BookID> <Title>Perl Cookbook</Title> <ISBN>1-565-92243-3</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>4</BookID> <Title>Java Cookbook</Title> <ISBN>0-596-00170-3</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>5</BookID> <Title>JavaScript Application Cookbook</Title> <ISBN>1-565-92577-7</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>6</BookID> <Title>VB .Net Language in a Nutshell</Title> <ISBN>0-596-00092-8</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>7</BookID> <Title>Programming Visual Basic .Net</Title> <ISBN>0-596-00093-6</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>8</BookID> <Title>Programming C#</Title> <ISBN>0-596-00117-7</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>9</BookID> <Title>.Net Framework Essentials</Title> <ISBN>0-596-00165-7</ISBN> <Publisher>O'Reilly</Publisher> </Book> <Book> <BookID>10</BookID> <Title>COM and .Net Component Services</Title> <ISBN>0-596-00103-7</ISBN> <Publisher>O'Reilly</Publisher> </Book> </Root> 

Example 18-8. Upload file and process (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH18FileUploadAndProcessVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH18FileUploadAndProcessVB" Title="File Upload And Process" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > File Upload And Process (VB) </div> <!-- The following table is displayed when the user is uploading a file --> <table  runat="server" align="center" width="60%" 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> <!-- The following gridView is displayed to show the data from the uploaded file --> <asp:GridView  runat="server"  AutoGenerateColumns="true"  BorderColor="#000080"  BorderStyle="Solid"  BorderWidth="2px"  Caption=""  HorizontalAlign="Center"  Width="90%" > <HeaderStyle HorizontalAlign="Center" Css /> <RowStyle css /> <AlternatingRowStyle css /> </asp:GridView> </asp:Content> 

Example 18-9. Upload file and process code-behind (.vb)

 Option Explicit On Option Strict On Imports System.Data Imports System.IO Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code-behind for ''' CH18FileUploadAndProcessVB.aspx ''' </summary> Partial Class CH18FileUploadAndProcessVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load If (Not Page.IsPostBack) Then 'make the table containing the upload controls visible and 'the gridview with the uploaded data invisible tabUpload.Visible = True gvUploadedData.Visible = False End If End Sub 'Page_Load '************************************************************************* ' ' ROUTINE: btnUpload_ServerClick ' ' DESCRIPTION: '------------------------------------------------------------------------ ''' <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) Dim dSet As DataSet 'make sure file was specified and was found If ((fuUpload.HasFile) AndAlso _  (fuUpload.PostedFile.ContentType.Equals("text/xml"))) Then 'make the table containing the upload controls invisible and  'the datagrid with the uploaded data visible tabUpload.Visible = False gvUploadedData.Visible = True 'load uploaded data into the dataset dSet = New DataSet dSet.ReadXml(fuUpload.FileContent) 'bind the data to the datagrid on the form gvUploadedData.DataSource = dSet gvUploadedData.DataBind() Else 'production code should notify user of upload error here End If End Sub 'btnUpload_ServerClick End Class 'CH18FileUploadAndProcessVB End Namespace 

Example 18-10. Upload file and process code-behind (.cs)

 using System; using System.Data; using System.IO; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code-behind for /// CH18FileUploadAndProcessCS.aspx /// </summary> public partial class CH18FileUploadAndProcessCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // make the table containing the upload controls visible and // the gridview with the uploaded data invisible tabUpload.Visible = true; gvUploadedData.Visible = false; } } // Page_Load ///*********************************************************************** /// <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) { DataSet dSet; // make sure file was specified and was found if ((fuUpload.HasFile) && (fuUpload.PostedFile.ContentType.Equals("text/xml"))) { // make the table containing the upload controls invisible and // the datagrid with the uploaded data visible tabUpload.Visible = false; gvUploadedData.Visible = true; // load uploaded data into the dataset dSet = new DataSet(); dSet.ReadXml(fuUpload.FileContent); // bind the data to the datagrid on the form gvUploadedData.DataSource = dSet; gvUploadedData.DataBind(); } else { // production code should notify user of upload error here } } // btnUpload_ServerClick } // CH18FileUploadAndProcessCS } 



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