1
Answer

How to save image as binary data in database using jquery?

Linto P Thomas

Linto P Thomas

9y
1.1k
1
How to save image as binary data in database using jquery in asp.net and also i want to retrieve the image on the current page while click on a button. If any one can help me please. Thanks in advance. Here I attached same I done using cs page but I want to do with jquery. Please help me.
 
 
Answers (1)
0
Susovan Biswas

Susovan Biswas

NA 10 0 9y
Logic:- 
 
Use HttpFileCollection and System.IO  classes.
 
In the database, the field which saves the image should be of varbinary datatype. 
 
In your Page Load  Event iterate through each HttpPostedFile in the HttpFileCollection class.
Save it temporarily in a folder. Access the save file in a FileStream. Take a byte variable and read the bytes of the declared FileStream into the byte variable. 
 
Send the byte to the database using Data Command Object with the help of Parameters.Add() .Value function. 
 
On successfull saving in database,  delete the file save in the temporary folder.
 
Code Help :-
 
HttpFileCollection  hfc = HttpContext.Current.Request.Files;
if(hfc.Count > 0)
{
   for(int i = 0; i< hfc.count; i++)
      {
          HttpPostedFile hpf = hfc[i];
          string path = HttpContext.Current.Server.MapPath("Path to save the http posted file"); 
         string imageName = hpf.FileName; 
         InsertPic(imageName);
      } 
 
 
private void InsertPic(string imagename)
{
   try
   {
      string path = HttpContext.Current.Server.MapPath("Path where you saved the http posted file");
      FileStream fsImage = new FileStream(path + @imagename, FileMode.Open, FileAccess.Read);
         //a byte array to read the image
         byte[] imgdata = new byte[fsImage.Length];
         fsImage.Read(imgdata, 0, System.Convert.ToInt32(fsImage.Length));
         string qry = "INSERT INTO TableName(imageField)VALUES(@imageField)";
         SqlCommand cmd = new SqlCommand(qry, SqlConnection);
         cmd.Parameters.Add("@imageField", SqlDbType.VarBinary).Value = imgdata;
          SqlConnection.Open();
         cmd.ExecuteNonQuery(); 
         fsImage.Dispose();
         System.IO.File.Delete(HttpContext.Current.Server.MapPath("Path where you saved the http posted file") + imagename);
      }
     catch (Exception ex)
     {
     }
      finally
      {
           SqlConnection.Close();
      } 
}
 
______________________________________________________________________________ 
 Worked for me.