Kirk Evans Blog

.NET From a Markup Perspective

Web App Design: Avoid Writing to Disk

I get this question about once per month:



I have a web app that accepts an image or XML document.  I need to save it to the database.  I first save it to file, then how do I get the file uploaded to the database?


The short answer is: you don’t.  If you don’t need to hit the disk, then just say no.  Instead, get the bytes from the request stream that you are interested in (the bytes representing the image or XML document) and stick them directly into the database.

if (this.FileUpload1.HasFile)
{
if ((this.FileUpload1.PostedFile.ContentType == “image/pjpeg”)
&& (this.FileUpload1.PostedFile.ContentLength < 100000 ))
{
SqlConnection cn = new SqlConnection(“Database=AdventureWorks;
Server=(local);Integrated Security=true;”);
cn.Open();
SqlCommand insert = new SqlCommand(
“INSERT INTO Production.ProductPhoto(LargePhoto, ModifiedDate) VALUES (@photo,getdate())”,
cn);
SqlParameter param = insert.CreateParameter();
param.ParameterName = “@photo”;
param.SqlDbType = SqlDbType.VarBinary;
param.Direction = ParameterDirection.Input;
param.Value = FileUpload1.FileBytes;
insert.Parameters.Add(param);
try
{
int rows = insert.ExecuteNonQuery();
}
catch (SqlException oops)
{
Response.Write(oops.ToString());
}
finally
{
insert.Dispose();
cn.Close();
cn.Dispose();
}
}
}

This example is using the FileUpload control for ASP.NET, but the effect is the same for a posted XML document: you just acquire the byte array for the stream and stick that directly into the database, no need to hit the disk.