Saving Images in a SQL database using ASP.Net

Monday, July 5, 2004

The ability to display images in a web application is a common requirement. There are two ways you can do this, either store images in a SQL database using the Binary Large Object (commonly know as BLOB) data type, or store the image on the disk. There are pro’s and cons to each of these methods, but in this article we’re going to learn how to store images into a SQL database.  

For the purpose of this article I have created a table in SQL Server called Images, with three columns, Image Name, Image Type and the Image itself. Now let’s take a look at the form we are going to use, to upload images to this table. 

    <form id="Form1" method="post" runat="server" 
               enctype="multipart/form-data">
      <br> <br>
      <asp:panel id="Panel1" runat="server"
             style="Z-INDEX: 102; LEFT: 120px; POSITION: absolute; TOP: 120px"
             Width="400px" Height="180px">
         <br> <br>
        <br>Select File :
        <input id="File1" type="file" name="File1" runat="server">
        <br> <br>
        <input id="Submit1" type="submit"
                value="Upload the files >" name="Submit1"
                runat="server">
         <br> <br>
         <asp:Label id="Label1" runat="server"></asp:Label>
       </asp:panel>
</form>

 Note: that the form enctype is multipart/form-data. This is necessary when we upload client files to a server.

So far, this looks pretty straightforward. Let’s take a look at the code which will process this request. To start with we see that File1 is derived from the HtmlInputfileclass 

    protected System.Web.UI.HtmlControls.HtmlInputFile File1;

This allows programmatic access to the HTML <input type= file> element on the server.  We are going to use the PostedFile class to get the properties of the client image file. In the following piece of code we use the ContentLength and ContentType methods of this class to get the length, and type of the image file. 

HttpPostedFile selectedFile = File1.PostedFile;
int imageLength = selectedFile.ContentLength;
string imageType = selectedFile.ContentType;

If we were going to save this file to the server, all we need to do, is use the SaveAs method. In this case we are going to store the image in a SQL database, so we need to convert it into a format that SQL can understand. We are going to create a byte array. The size of the array is the length of the image that we were able to retrieve using the Contentlength property of the HttpPostedFile class. 

binaryImagedata = new byte[imageLength];

The HttpPostedFile class also has an InputStream method, which returns the image data in bytes. We are going to use this to populate our byte array

selectedFile.InputStream.Read(binaryImagedata,0,imageLength);

We now have all the fields needed (imageLength, File1.PostedFile.FileName and binaryImagedata) to populate the database.
This covers the basics of how to upload an image to a database. In a real application, there are other things we might want to do, for example some validation checks. By checking the value of selectedFile.ContentLength you can enforce size restrictions on the image file. A ContentLength of 0, indicates that the file either does not exist or an empty file is being uploaded. The following code would check for empty files :

if (selectedFile.ContentLength==0) 
   {
   errs ="0 length file ";
   }

 Note: The default file size that can be uploaded is 4MB, and a larger size will cause .Net to throw an exception. To change the default size for all applications on the server, the machine.config file will need to be modified. In the httpRuntime section, there is a maxRequestLength attribute, <maxRequestLength="4096">. Change the length to whatever new default you need.

If you want to make the change for only a single application however, then this setting can be overridden in the web.config file of the application in question. You would need to create a <httpRuntime> section and add the maxRequestLength attribute with the size you require. For further information on this topic, see the documentation for the
HttpRuntime element

We can also check the value of selectedFile.ContentType and verify if the file type is one we allow to be uploaded. The ContentType returns the MIME encoding in string format of the request. This is typically in category / subcategory format. Some common types include

"text/HTML" or "image/GIF". To ensure that the user can only upload GIF files, add the following code

if (selectedFile.ContentType.ToLower() != @"image/gif") 
  {

 

  errs +="Invalid filetype";

 

   } 

 

In some cases we might also need to check for the dimensions of the image. Often, an application has a pre-determined space to display the image, and you might want to ensure that the height and width of the image match the allotted space. The HttpPostedFile class is not limited to just image files, so does not provide for any methods to retrieve this information. To retrieve further information about images, we are going to use the image class in the System.Drawing namespace. For the purpose of this article we are only interested in the length and width of the image, however there is a lot more that you can do with this class, refer to System.Drawing.Image . To start with we create an Image object  

System.Drawing.Image drawingImage = null; 

 

The next step is to read the byte array binaryImagedata into our Image object.  

drawingImage = System.Drawing.Image.FromStream(new System.IO.MemoryStream(binaryImagedata)); 

 

Now we have access to both the height and width of the array, so if your application requires your images have a length and width of 300 px you would use the following code

If ((drawingImage.Width != 300) && (drawingImage.Height != 300)) { 
    Errs = “Image is the wrong size”;

 

} 

 

 

Hopefully this article covers all the basic elements of uploading images to a SQL database. To retrieve images to display in a web form - Displaying SQL Images in an ASP.Net datagrid,.

Login to Download code

 

by Llama Lopon

by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!