Saturday, September 6, 2014

Inserting and Retrieving Images From Database

Database: Sql Server 2008 R2
Platform: ASP.NET 4.0 using C#




Inserting into database


Create a table Say EmployeePhoto

Table Structure:

EmployeePhotoId           INT         (PK)

EmployeeNo                  VARCHAR(10)

EmployeePhoto              IMAGE


Step-1: Upload image file to your project folder 


string strFileName = fupEmpPhoto.FileName;



try

{

  if (fupEmpPhoto.HasFile)

  {

     fupEmpPhoto.PostedFile.SaveAs(Server.MapPath("Uploads/" + strFileName));

  }

}

catch (Exception objExp)

{

     lblAlert.Text = objExp.Message;

}



Step-2: Convert Image file in byte array


string strPhotoPath = Server.MapPath("Uploads/" + fupEmpPhoto.FileName);

byte[] EmpPhoto = getPhoto(strPhotoPath);



Step-3: Simply insert into database.



Step-4: Delete uploaded file from project folder.

if (File.Exists(Server.MapPath("Uploads/" + fupEmpPhoto.FileName)))

            File.Delete(Server.MapPath("Uploads/" + fupEmpPhoto.FileName));





Now retrieving image from database

Suppose we need to get image of particular employee, using simple select query we will get the data into data table say dt. Now main challenge is to convert byte array data into image file.

if(dt.Rows.Count>0)

{

            //string strfn = Convert.ToString(DateTime.Now.ToFileTime()) + ".jpg";

            byte[] pic = (byte[])dt.Rows[0][0];



            if (File.Exists(Server.MapPath("Uploads/temp.jpg")))

                File.Delete(Server.MapPath("Uploads/temp.jpg"));



            FileStream fs = new FileStream(Server.MapPath("Uploads/temp.jpg"),           FileMode.CreateNew, FileAccess.Write);

            fs.Write(pic, 0, pic.Length);

           

            fs.Flush();

            fs.Close();

           

            imgEmpPhoto.ImageUrl = "Uploads/temp.jpg";           

}












No comments:

Post a Comment