15.4. Storing the Contents of an Uploaded File in a Database

Problem

You need to provide the ability for a user to upload a file to the web server that will be processed later, so you want to store the file in the database.

Solution

Implement the solution described in Recipe 15.2, but when the user clicks a button to initiate the upload process, instead of writing the file to the filesystem, use the input stream containing the uploaded file along with ADO.NET to write the file to a database.

For the .aspx file, follow the steps for implementing the .aspx file in Recipe 15.2.

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

  1. Process the Upload button click event and verify that a file has been uploaded.

  2. Open a connection to the database.

  3. Build the command used to add the data to the database and insert the file data.

The application we’ve written to demonstrate this solution uses the same .aspx file as Recipe 15.2s example (see Example 15-4). The code-behind for our application is shown in Example 15-11 (VB) and Example 15-12 (C#). The initial output is the same as Recipe 15.2s example output and is shown in Figure 15-3.

Discussion

Storing an uploaded file in a database is useful when a complete, unmodified record of the upload is required to be set apart from the web server’s filesystem, when the file contains sensitive information, or when additional metadata needs to be stored with the file. It is also quite common to store the uploaded data in a database ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.