Recipe 18.5. 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 18.2. 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 18.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 18.2's example (see Example 18-4). The code-behind for our application is shown in Examples 18-11 (VB) and 18-12 (C#). The initial output is the same as Recipe 18.2's example output and is shown in Example 18-3.

Discussion

Storing an uploaded file in a database is useful when a complete, unmodified upload record 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 common to store the uploaded data in a database and then process the data immediately or by another program outside of the web application. We will not go into that here, though.

The example we've written to demonstrate this solution includes a button to initiate the upload process and uses the input stream containing the uploaded file along with ADO.NET to write the file to a database. The example uses the same code as Recipe 18.2, changing only the actions performed in the btnUpload_ServerClick method of the code-behind. After verifying that a file has been uploaded, a connection is made to the database.

We then create an OleDbCommand with the CommandText property set to a parameterized SQL INSERT statement to store the filename, the file size, and the contents of the file in the database. We use a parameterized query to handle the binary data contained in the file.

The FileData column of our database needs to be able to handle the binary data contained in the file. For SQL Server, the data type should be VarBinary or image. Even if the uploaded files are text files, use a binary field for storage of the data. Text files can contain Unicode or utf-8-encoded characters that SQL Server cannot store in text fields, which results in a SQL exception being thrown.

Next, three parameters are added to the parameter collection of the command object and the values are set with the uploaded file information. Because our example uses OleDb, which does not support named parameters as the SQL provider does, the parameters must be added in the same order they appear in the INSERT statement.

The Filename and Filesize parameters require creating the parameter and setting the value. The Filedata parameter is created in the same manner; however, the value must be set to a byte array. A byte array of the uploaded file data is available using the FileBytes property of the FileUpload control.

The last step is to set the connection property of the command to the connection opened earlier and executing the command. The ExecuteNonQuery method of the command object is used because no data is being returned by the command.

See Also

Recipe 18.2 for the base code used for this recipe and a discussion of the size limits on uploaded files

Example 18-11. Storing uploaded file to database code-behind (.vb)

 Protected Sub btnUpload_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim dbConn As OleDbConnection = Nothing Dim dcmd As OleDbCommand Dim strConnection As String Try 'make sure file was uploaded If (fuUpload.HasFile) Then 'get the connection string from web.config and open a connection 'to the database strConnection = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dbConn = New OleDbConnection(strConnection) dbConn.Open() 'build the command used to add the data to the database dcmd = New OleDbCommand dcmd.CommandText = "INSERT INTO FileUpload " & _    "(Filename, Filesize, FileData) " & _    "VALUES " & _    "(?, ?, ?)" 'create the paramters and set the values for the file data dcmd.Parameters.Add(New OleDbParameter("Filename", _ fuUpload.FileName)) dcmd.Parameters.Add(New OleDbParameter("Filesize", _ fuUpload.PostedFile.ContentLength)) dcmd.Parameters.Add(New OleDbParameter("FileData", _ fuUpload.FileBytes)) 'insert the file data dcmd.Connection = dbConn dcmd.ExecuteNonQuery() End If Finally If (Not IsNothing(dbConn)) Then dbConn.Close() End If End Try End Sub 'btnUpload_ServerClick 

Example 18-12. Storing uploaded file to database code-behind (.cs)

 protected void btnUpload_ServerClick(Object sender,  System.EventArgs e) { OleDbConnection dbConn = null; OleDbCommand dcmd = null; String strConnection; try { // make sure file was uploaded if (fuUpload.HasFile) { // get the connection string from web.config and open a connection // to the database strConnection = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dbConn = new OleDbConnection(strConnection); dbConn.Open(); // build the command used to add the data to the database dcmd = new OleDbCommand(); dcmd.CommandText = "INSERT INTO FileUpload " +    "(Filename, Filesize, FileData) " +    "VALUES " +    "(?, ?, ?)"; // create the paramters and set the values for the file data dcmd.Parameters.Add(new OleDbParameter("Filename",    fuUpload.FileName)); dcmd.Parameters.Add(new OleDbParameter("Filesize", fuUpload.PostedFile.ContentLength)); dcmd.Parameters.Add(new OleDbParameter("FileData",    fuUpload.FileBytes)); // insert the file data dcmd.Connection = dbConn; dcmd.ExecuteNonQuery(); } } finally { if (dbConn != null) { dbConn.Close(); } } } // btnUpload_ServerClick 



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

Similar book on Amazon

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