Uploading Files (C#)

by Scott Mitchell

Download Sample App or Download PDF

Learn how to let users to upload binary files (such equally Word or PDF documents) to your Spider web site where they may be stored in either the server'south file system or the database.

Introduction

All of the tutorials we ve examined so far have worked exclusively with text information. Withal, many applications have information models that capture both text and binary data. An online dating site might allow users to upload a picture to acquaintance with their profile. A recruiting website might let users upload their resume as a Microsoft Word or PDF document.

Working with binary data adds a new set of challenges. Nosotros must determine how the binary information is stored in the application. The interface used for inserting new records has to exist updated to allow the user to upload a file from their estimator and extra steps must exist taken to display or provide a means for downloading a record due south associated binary information. In this tutorial and the next 3 we'll explore how to hurdle these challenges. At the finish of these tutorials we'll accept congenital a fully functional application that associates a motion-picture show and PDF brochure with each category. In this detail tutorial nosotros'll look at unlike techniques for storing binary information and explore how to enable users to upload a file from their calculator and accept information technology saved on the web server s file system.

Notation

Binary data that is part of an application s data model is sometimes referred to as a BLOB, an acronym for Binary Large OBject. In these tutorials I have chosen to use the terminology binary data, although the term Blob is synonymous.

Stride 1: Creating the Working with Binary Data Web Pages

Before nosotros begin to explore the challenges associated with adding support for binary information, permit due south get-go have a moment to create the ASP.NET pages in our website project that we'll demand for this tutorial and the next 3. First by adding a new folder named BinaryData. Next, add together the following ASP.NET pages to that folder, making sure to associate each page with the Site.master master page:

  • Default.aspx
  • FileUpload.aspx
  • DisplayOrDownloadData.aspx
  • UploadInDetailsView.aspx
  • UpdatingAndDeleting.aspx

Add the ASP.NET Pages for the Binary Data-Related Tutorials

Figure 1: Add together the ASP.NET Pages for the Binary Data-Related Tutorials

Like in the other folders, Default.aspx in the BinaryData binder will list the tutorials in its section. Remember that the SectionLevelTutorialListing.ascx User Control provides this functionality. Therefore, add this User Control to Default.aspx by dragging it from the Solution Explorer onto the page south Blueprint view.

Add the SectionLevelTutorialListing.ascx User Control to Default.aspx

Figure two: Add the SectionLevelTutorialListing.ascx User Control to Default.aspx (Click to view full-size image)

Lastly, add these pages as entries to the Web.sitemap file. Specifically, add together the following markup after the Enhancing the GridView <siteMapNode>:

              <siteMapNode      championship="Working with Binary Data"      url="~/BinaryData/Default.aspx"      description="Extend the data model to include collecting binary data.">          <siteMapNode          title="Uploading Files"          url="~/BinaryData/FileUpload.aspx"          description="Examine the different ways to shop binary data on the                       web server and run across how to accept uploaded files from users                       with the FileUpload control." />     <siteMapNode          championship="Display or Download Binary Data"          url="~/BinaryData/DisplayOrDownloadData.aspx"          description="Let users view or download the captured binary data." />     <siteMapNode          title="Adding New Binary Information"          url="~/BinaryData/UploadInDetailsView.aspx"          clarification="Learn how to augment the inserting interface to                       include a FileUpload control." />     <siteMapNode          championship="Updating and Deleting Existing Binary Data"          url="~/BinaryData/UpdatingAndDeleting.aspx"          description="Learn how to update and delete existing binary data." /> </siteMapNode>                          

Later on updating Web.sitemap, take a moment to view the tutorials website through a browser. The carte du jour on the left now includes items for the Working with Binary Data tutorials.

The Site Map Now Includes Entries for the Working with Binary Data Tutorials

Effigy 3: The Site Map Now Includes Entries for the Working with Binary Information Tutorials

Footstep 2: Deciding Where to Store the Binary Data

Binary data that is associated with the application s information model can be stored in one of 2 places: on the web server south file system with a reference to the file stored in the database; or direct within the database itself (see Figure 4). Each approach has its own set of pros and cons and merits a more detailed discussion.

Binary Data Can Be Stored On the File System or Directly in the Database

Effigy iv: Binary Data Can Be Stored On the File Arrangement or Directly in the Database (Click to view full-size image)

Imagine that we wanted to extend the Northwind database to acquaintance a moving picture with each product. One choice would be to store these image files on the web server south file system and tape the path in the Products table. With this arroyo, we d add an ImagePath column to the Products table of type varchar(200), perhaps. When a user uploaded a picture for Chai, that picture might be stored on the web server s file organisation at ~/Images/Tea.jpg, where ~ represents the awarding s concrete path. That is, if the web site is rooted at the physical path C:\Websites\Northwind\, ~/Images/Tea.jpg would be equivalent to C:\Websites\Northwind\Images\Tea.jpg. After uploading the image file, we d update the Chai tape in the Products table so that its ImagePath cavalcade referenced the path of the new image. We could use ~/Images/Tea.jpg or just Tea.jpg if nosotros decided that all product images would be placed in the awarding south Images binder.

The principal advantages of storing the binary information on the file system are:

  • Ease of implementation as we'll come across before long, storing and retrieving binary data stored straight within the database involves a fleck more code than when working with data through the file organisation. Additionally, in lodge for a user to view or download binary information they must be presented with a URL to that data. If the data resides on the spider web server s file system, the URL is straightforward. If the information is stored in the database, however, a web page needs to be created that will call back and return the data from the database.
  • Wider access to the binary information the binary data may demand to be accessible to other services or applications, ones that cannot pull the data from the database. For example, the images associated with each product might too need to be available to users through FTP, in which case we d want to store the binary data on the file system.
  • Performance if the binary data is stored on the file system, the demand and network congestion betwixt the database server and spider web server will be less than if the binary data is stored directly within the database.

The main disadvantage of storing binary data on the file organisation is that it decouples the data from the database. If a record is deleted from the Products table, the associated file on the web server s file organization is not automatically deleted. We must write extra lawmaking to delete the file or the file system will go cluttered with unused, orphaned files. Furthermore, when backing upwardly the database, we must make sure to brand backups of the associated binary information on the file organization, too. Moving the database to another site or server poses like challenges.

Alternatively, binary data can exist stored directly in a Microsoft SQL Server 2005 database by creating a column of type varbinary. Like with other variable length data types, you tin specify a maximum length of the binary information that tin be held in this column. For instance, to reserve at most 5,000 bytes use varbinary(5000); varbinary(MAX) allows for the maximum storage size, near two GB.

The main reward of storing binary data directly in the database is the tight coupling between the binary information and the database record. This greatly simplifies database administration tasks, like backups or moving the database to a unlike site or server. Also, deleting a record automatically deletes the corresponding binary data. At that place are too more subtle benefits of storing the binary data in the database. See Storing Binary Files Directly in the Database Using ASP.NET 2.0 for a more in-depth discussion.

Annotation

In Microsoft SQL Server 2000 and earlier versions, the varbinary data type had a maximum limit of 8,000 bytes. To shop up to two GB of binary data the image data blazon needs to exist used instead. With the add-on of MAX in SQL Server 2005, still, the image data type has been deprecated. It southward still supported for backwards compatibility, merely Microsoft has appear that the paradigm data type will be removed in a future version of SQL Server.

If you lot are working with an older data model you may run across the image data blazon. The Northwind database s Categories tabular array has a Picture column that tin be used to store the binary information of an image file for the category. Since the Northwind database has its roots in Microsoft Admission and earlier versions of SQL Server, this column is of type image.

For this tutorial and the next three, nosotros'll utilise both approaches. The Categories tabular array already has a Picture column for storing the binary content of an prototype for the category. Nosotros'll add an boosted column, BrochurePath, to store a path to a PDF on the web server s file arrangement that tin can be used to provide a print-quality, polished overview of the category.

Step 3: Adding theBrochurePathCavalcade to theCategoriesTable

Currently the Categories tabular array has but four columns: CategoryID, CategoryName, Description, and Picture. In addition to these fields, we need to add together a new one that will point to the category south brochure (if one exists). To add this cavalcade, become to the Server Explorer, drill down into the Tables, right-click on the Categories table and choose Open Tabular array Definition (see Figure five). If you do not come across the Server Explorer, bring it up past selecting the Server Explorer option from the View carte, or hitting Ctrl+Alt+South.

Add a new varchar(200) column to the Categories table that is named BrochurePath and allows Nil s and click the Salvage icon (or hitting Ctrl+S).

Add a BrochurePath Column to the Categories Table

Figure v: Add a BrochurePath Column to the Categories Table (Click to view total-size image)

Stride 4: Updating the Compages to Use theMoving pictureandBrochurePathColumns

The CategoriesDataTable in the Data Admission Layer (DAL) currently has four DataColumn due south defined: CategoryID, CategoryName, Description, and NumberOfProducts. When we originally designed this DataTable in the Creating a Data Access Layer tutorial, the CategoriesDataTable simply had the starting time 3 columns; the NumberOfProducts cavalcade was added in the Master/Item Using a Bulleted List of Master Records with a Details DataList tutorial.

As discussed in Creating a Data Access Layer, the DataTables in the Typed DataSet make upward the business concern objects. The TableAdapters are responsible for communicating with the database and populating the business concern objects with the query results. The CategoriesDataTable is populated by the CategoriesTableAdapter, which has three data retrieval methods:

  • GetCategories() executes the TableAdapter s main query and returns the CategoryID, CategoryName, and Description fields of all records in the Categories table. The main query is what is used past the car-generated Insert and Update methods.
  • GetCategoryByCategoryID(categoryID) returns the CategoryID, CategoryName, and Description fields of the category whose CategoryID equals categoryID.
  • GetCategoriesAndNumberOfProducts() - returns the CategoryID, CategoryName, and Description fields for all records in the Categories table. Also uses a subquery to return the number of products associated with each category.

Observe that none of these queries return the Categories table southward Motion picture or BrochurePath columns; nor does the CategoriesDataTable provide DataColumn south for these fields. In lodge to work with the Picture and BrochurePath properties, we need to kickoff add them to the CategoriesDataTable and and so update the CategoriesTableAdapter course to render these columns.

Adding thePicture showandBrochurePath``DataColumn s

Start by adding these two columns to the CategoriesDataTable. Right-click on the CategoriesDataTable s header, select Add from the context card and and so choose the Column option. This volition create a new DataColumn in the DataTable named Column1. Rename this column to Movie. From the Backdrop window, set the DataColumn s DataType belongings to System.Byte[] (this is non an pick in the drop-downwards list; you need to type it in).

Create a DataColumn Named Picture whose DataType is System.Byte[]

Effigy vi: Create a DataColumn Named Picture whose DataType is System.Byte[] (Click to view full-size image)

Add another DataColumn to the DataTable, naming it BrochurePath using the default DataType value (Organisation.Cord).

Returning thePictureandBrochurePathValues from the TableAdapter

With these two DataColumn s added to the CategoriesDataTable, we re ready to update the CategoriesTableAdapter. We could take both of these cavalcade values returned in the main TableAdapter query, but this would bring back the binary data every time the GetCategories() method was invoked. Instead, let south update the primary TableAdapter query to bring back BrochurePath and create an additional data retrieval method that returns a detail category s Film column.

To update the principal TableAdapter query, correct-click on the CategoriesTableAdapter southward header and choose the Configure choice from the context bill of fare. This brings up the Table Adapter Configuration Wizard, which nosotros ve seen in a number of past tutorials. Update the query to bring back the BrochurePath and click Terminate.

Update the Column List in the SELECT Statement to Also Return BrochurePath

Figure 7: Update the Column List in the SELECT Statement to Also Return BrochurePath (Click to view full-size prototype)

When using ad-hoc SQL statements for the TableAdapter, updating the column list in the chief query updates the column listing for all of the SELECT query methods in the TableAdapter. That means the GetCategoryByCategoryID(categoryID) method has been updated to return the BrochurePath column, which might be what nosotros intended. Notwithstanding, information technology too updated the column listing in the GetCategoriesAndNumberOfProducts() method, removing the subquery that returns the number of products for each category! Therefore, we need to update this method s SELECT query. Right-click on the GetCategoriesAndNumberOfProducts() method, cull Configure, and revert the SELECT query dorsum to its original value:

              SELECT CategoryID, CategoryName, Description,         (SELECT COUNT(*)              FROM Products p              WHERE p.CategoryID = c.CategoryID)         equally NumberOfProducts FROM Categories c                          

Adjacent, create a new TableAdapter method that returns a particular category southward Picture cavalcade value. Correct-click on the CategoriesTableAdapter s header and cull the Add Query option to launch the TableAdapter Query Configuration Sorcerer. The starting time step of this wizard asks us if nosotros want to query data using an advertising-hoc SQL argument, a new stored process, or an existing one. Select Employ SQL statements and click Next. Since we will be returning a row, choose the SELECT which returns rows option from the second step.

Select the Use SQL statements Option

Figure eight: Select the Use SQL statements Pick (Click to view full-size epitome)

Since the Query Will Return a Record from the Categories Table, Choose SELECT which returns rows

Figure 9: Since the Query Will Render a Record from the Categories Tabular array, Choose SELECT which returns rows (Click to view total-size image)

In the third footstep, enter the following SQL query and click Next:

              SELECT     CategoryID, CategoryName, Description, BrochurePath, Picture FROM       Categories WHERE      CategoryID = @CategoryID                          

The last pace is to choose the name for the new method. Use FillCategoryWithBinaryDataByCategoryID and GetCategoryWithBinaryDataByCategoryID for the Fill a DataTable and Return a DataTable patterns, respectively. Click Finish to complete the magician.

Choose the Names for the TableAdapter s Methods

Effigy 10: Choose the Names for the TableAdapter s Methods (Click to view full-size image)

Note

After completing the Table Adapter Query Configuration Wizard you may see a dialog box informing you lot that the new control text returns information with schema different from the schema of the primary query. In curt, the wizard is noting that the TableAdapter s main query GetCategories() returns a dissimilar schema than the 1 we just created. But this is what we desire, so you tin can condone this message.

Also, keep in heed that if you are using ad-hoc SQL statements and use the wizard to modify the TableAdapter due south main query at some later point in time, it will modify the GetCategoryWithBinaryDataByCategoryID method s SELECT argument s column list to include simply those columns from the master query (that is, it volition remove the Moving picture column from the query). You will take to manually update the cavalcade listing to render the Flick column, similar to what nosotros did with the GetCategoriesAndNumberOfProducts() method earlier in this step.

After adding the two DataColumn south to the CategoriesDataTable and the GetCategoryWithBinaryDataByCategoryID method to the CategoriesTableAdapter, these classes in the Typed DataSet Designer should look like the screenshot in Figure 11.

The DataSet Designer Includes the New Columns and Method

Figure 11: The DataSet Designer Includes the New Columns and Method

Updating the Business organisation Logic Layer (BLL)

With the DAL updated, all that remains is to broaden the Business organization Logic Layer (BLL) to include a method for the new CategoriesTableAdapter method. Add together the following method to the CategoriesBLL class:

              [System.ComponentModel.DataObjectMethodAttribute     (System.ComponentModel.DataObjectMethodType.Select, faux)]  public Northwind.CategoriesDataTable      GetCategoryWithBinaryDataByCategoryID(int categoryID) {     return Adapter.GetCategoryWithBinaryDataByCategoryID(categoryID); }                          

Step 5: Uploading a File From the Client to the Spider web Server

When collecting binary information, oftentimes this data is supplied by an end user. To capture this data, the user needs to be able to upload a file from their computer to the web server. The uploaded data then needs to be integrated with the information model, which may mean saving the file to the web server s file arrangement and adding a path to the file in the database, or writing the binary contents directly into the database. In this stride nosotros'll look at how to permit a user to upload files from their computer to the server. In the next tutorial we'll turn our attention to integrating the uploaded file with data model.

ASP.Internet ii.0 s new FileUpload Web command provides a mechanism for users to send a file from their computer to the web server. The FileUpload control renders every bit an <input> element whose type attribute is gear up to file, which browsers display as a textbox with a Browse push button. Clicking the Scan button brings upward a dialog box from which the user can select a file. When the course is posted back, the selected file s contents are sent along with the postback. On the server-side, information about the uploaded file is accessible through the FileUpload command south properties.

To demonstrate uploading files, open the FileUpload.aspx folio in the BinaryData folder, drag a FileUpload control from the Toolbox onto the Designer, and prepare the control s ID property to UploadTest. Next, add a Button Web control setting its ID and Text properties to UploadButton and Upload Selected File, respectively. Finally, place a Characterization Web command beneath the Push, clear out its Text property and set its ID property to UploadDetails.

Add a FileUpload Control to the ASP.NET Page

Figure 12: Add a FileUpload Command to the ASP.NET Page (Click to view total-size image)

Figure 13 shows this page when viewed through a browser. Note that clicking the Browse button brings up a file selection dialog box, allowing the user to pick a file from their computer. Once a file has been selected, clicking the Upload Selected File push button causes a postback that sends the selected file s binary content to the web server.

The User Can Select a File to Upload from their Computer to the Server

Figure 13: The User Can Select a File to Upload from their Computer to the Server (Click to view total-size epitome)

On postback, the uploaded file can be saved to the file organization or its binary information can be worked with direct through a Stream. For this example, let s create a ~/Brochures folder and salvage the uploaded file at that place. Start past adding the Brochures folder to the site as a subfolder of the root directory. Next, create an upshot handler for the UploadButton s Click effect and add together the following lawmaking:

              protected void UploadButton_Click(object sender, EventArgs e) {     if (UploadTest.HasFile == false)     {         // No file uploaded!         UploadDetails.Text = "Please first select a file to upload...";                 }     else     {         // Display the uploaded file's details         UploadDetails.Text = string.Format(                 @"Uploaded file: {0}<br />                   File size (in bytes): {one:N0}<br />                   Content-blazon: {2}",                    UploadTest.FileName,                    UploadTest.FileBytes.Length,                   UploadTest.PostedFile.ContentType);         // Save the file         cord filePath =              Server.MapPath("~/Brochures/" + UploadTest.FileName);         UploadTest.SaveAs(filePath);     } }                          

The FileUpload control provides a diversity of backdrop for working with the uploaded data. For instance, the HasFile holding indicates whether a file was uploaded past the user, while the FileBytes property provides access to the uploaded binary data every bit an array of bytes. The Click effect handler starts by ensuring that a file has been uploaded. If a file has been uploaded, the Label shows the proper name of the uploaded file, its size in bytes, and its content-blazon.

Note

To ensure that the user uploads a file you can cheque the HasFile property and display a warning if it s fake, or you may employ the RequiredFieldValidator control instead.

The FileUpload s SaveAs(filePath) saves the uploaded file to the specified filePath. filePath must be a physical path (C:\Websites\Brochures\SomeFile.pdf) rather than a virtual path (/Brochures/SomeFile.pdf). The Server.MapPath(virtPath) method takes a virtual path and returns its corresponding physical path. Hither, the virtual path is ~/Brochures/fileName, where fileName is the proper name of the uploaded file. See Using Server.MapPath for more information on virtual and physical paths and using Server.MapPath.

Subsequently completing the Click event handler, take a moment to test out the page in a browser. Click the Scan button and select a file from your hard drive and so click the Upload Selected File button. The postback will ship the contents of the selected file to the spider web server, which will and then display information virtually the file before saving it to the ~/Brochures folder. Afterward uploading the file, return to Visual Studio and click the Refresh button in the Solution Explorer. Y'all should run across the file you only uploaded in the ~/Brochures folder!

The File EvolutionValley.jpg Has Been Uploaded to the Web Server

Figure 14: The File EvolutionValley.jpg Has Been Uploaded to the Web Server (Click to view full-size prototype)

EvolutionValley.jpg Was Saved to the ~/Brochures Folder

Figure 15: EvolutionValley.jpg Was Saved to the ~/Brochures Binder

Subtleties with Saving Uploaded Files to the File Arrangement

There are several subtleties that must be addressed when saving uploading files to the web server s file system. First, there s the effect of security. To save a file to the file system, the security context nether which the ASP.NET page is executing must take Write permissions. The ASP.Cyberspace Development Web Server runs under the context of your current user account. If you lot are using Microsoft s Net Information Services (IIS) as the web server, the security context depends on the version of IIS and its configuration.

Another challenge of saving files to the file system revolves around naming the files. Currently, our page saves all of the uploaded files to the ~/Brochures directory using the aforementioned proper name as the file on the client southward reckoner. If User A uploads a brochure with the name Brochure.pdf, the file will be saved as ~/Brochure/Brochure.pdf. But what if sometime afterwards User B uploads a different brochure file that happens to have the aforementioned filename (Brochure.pdf)? With the code we have now, User A south file will be overwritten with User B s upload.

There are a number of techniques for resolving file name conflicts. One choice is to prohibit uploading a file if at that place already exists one with the aforementioned proper name. With this approach, when User B attempts to upload a file named Brochure.pdf, the arrangement would not save their file and instead display a message informing User B to rename the file and try again. Another approach is to save the file using a unique file name, which could exist a globally unique identifier (GUID) or the value from the corresponding database tape s primary key column(s) (assuming that the upload is associated with a particular row in the information model). In the side by side tutorial we'll explore these options in more than detail.

Challenges Involved with Very Large Amounts of Binary Data

These tutorials assume that the binary information captured is small in size. Working with very large amounts of binary data files that are several megabytes or larger introduces new challenges that are beyond the telescopic of these tutorials. For example, by default ASP.Net will reject uploads of more than iv MB, although this tin be configured through the <httpRuntime> chemical element in Web.config. IIS imposes its own file upload size limitations, too. Run across IIS Upload File Size for more information. Furthermore, the time taken to upload large files might exceed the default 110 seconds ASP.NET will wait for a request. There are besides retentivity and performance issues that arise when working with large files.

The FileUpload control is impractical for large file uploads. As the file s contents are being posted to the server, the cease user must patiently wait without whatever confirmation that their upload is progressing. This is not so much an issue when dealing with smaller files that tin can be uploaded in a few seconds, merely tin can exist an result when dealing with larger files that may take minutes to upload. In that location are a variety of third-political party file upload controls that are better suited for handling big uploads and many of these vendors provide progress indicators and ActiveX upload managers that present a much more polished user experience.

If your application needs to handle large files, you'll need to carefully investigate the challenges and find suitable solutions for your particular needs.

Summary

Building an awarding that needs to capture binary data introduces a number of challenges. In this tutorial we explored the first 2: deciding where to store the binary information and allowing a user to upload binary content through a web page. Over the next three tutorials, nosotros'll see how to associate the uploaded data with a record in the database equally well as how to display the binary data alongside its text data fields.

Happy Programming!

Further Reading

For more information on the topics discussed in this tutorial, refer to the post-obit resources:

  • Using Big-Value Data Types
  • FileUpload Command QuickStarts
  • The ASP.NET 2.0 FileUpload Server Command
  • The Nighttime Side of File Uploads

Almost the Author

Scott Mitchell, author of seven ASP/ASP.Cyberspace books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies since 1998. Scott works equally an independent consultant, trainer, and writer. His latest book is Sams Teach Yourself ASP.Net two.0 in 24 Hours. He can exist reached at mitchell@4GuysFromRolla.com. or via his blog, which can exist found at http://ScottOnWriting.Internet.

Special Thanks To

This tutorial series was reviewed past many helpful reviewers. Lead reviewers for this tutorial were Teresa Irish potato and Bernadette Leigh. Interested in reviewing my upcoming MSDN articles? If then, drib me a line at mitchell@4GuysFromRolla.com.