May 26, 2014

Save Image to Sql Server

Sql server allows for the "Image" data type that can be used to save images in databases. In this post, I will show how to save an image to the database. In a nutshell, I will use a File Upload control to upload the image and use entity framework to save the image.



Here is my database table's structure.
image

And here is the entity model generated from the database.
image
The front end of the application is simple and contains a FileUpload control, a button and a Label control.
Front end
  1. <asp:FileUpload ID="fu1" runat="server" />
  2. <asp:Button ID="b1" runat="server" Text="Add Image" OnClick="b1_Click" /><br />
  3. <asp:Label ID="LStatus" runat="server"></asp:Label>

When the button is clicked, the Stream object is obtained from the image using FileUpload.PostedFile.InputStream . The Stream is then saved in the database in the usual way.
Code behind
  1. protected void b1_Click(object sender, EventArgs e)
  2. {
  3.     if (fu1.HasFile)
  4.     {
  5.         string filename = fu1.PostedFile.FileName;
  6.         int size = fu1.PostedFile.ContentLength;
  7.         Stream fileStream = fu1.PostedFile.InputStream;
  8.  
  9.         if(SaveImage(fileStream, filename, size))
  10.             LStatus.Text += "Image saved successfully";
  11.         else
  12.             LStatus.Text += "Failed to save image";
  13.     }
  14. }
  15.  
  16. private bool SaveImage(Stream fileStream, string filename, int size)
  17. {
  18.     bool check = false;
  19.  
  20.     try
  21.     {
  22.         byte[] documentBytes = new byte[fileStream.Length];
  23.         fileStream.Read(documentBytes, 0, documentBytes.Length);
  24.  
  25.         ImgPrac im = new ImgPrac()
  26.         {
  27.             Name = filename,
  28.             Photo = documentBytes,
  29.             Size = size
  30.         };
  31.                         
  32.         using (ImgPracEntities en = new ImgPracEntities())
  33.         {
  34.             en.ImgPracs.Add(im);
  35.             en.SaveChanges();
  36.             check = true;
  37.         }
  38.     }
  39.     catch (Exception ex)
  40.     {
  41.         // handle exception
  42.     }
  43.  
  44.     return check;
  45. }

That’s it – you should be able to upload and save the image into a sql server database now.

0 comments:

Reference: Shahed Kazi at AspNetify.com