3
Answers

Get the images from Excel sheet and store in Local Folder...

keerthi sai

keerthi sai

7y
293
1
Hi..,
Plz Help me,
 
I have Excel File it contains lot of columns , 1 of  the columns contains  Images ,
i need to read images and store in Local folder  (physically),,,
plz help me... 
 
 
Answers (3)
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.