Wednesday, December 04, 2013

Uploading, storing, update, retrieving and displaying images/pictures into database asp.net C#


Final Outcome

How to allow user to upload, store, update, retrieve and display images into your database and web sever?

This short tutorial by me shows you the simplified method of storing your images and retrieving the images efficiently.

Scenario :
You are creating a website that allows you to upload, store, update and display profile image.

What you should already have:

Database prepared for testing (Set your ProfileImage as image type)

- ProfileRecordId   int    primary key (Set identity specification to yes)
- ProfileImage        image

You should have these webforms/files done at the end of this tutorial.
1) App_Code
2) addprofilepic.aspx
3) displayprofilepic.aspx
4) manageprofilepics.aspx
5) profileImageHandler.ashx
6) updateProfile.aspx
7) Unknown.aspx - empty webpage(just for redirecting)





NOTE: In this tutorial, I used a shortcut to connect the connection string. You can still use your normal connection string. However, if you wish to use the shortcut, remember to replace your connectionStrings line in your Web.config

 TO BE REPLACED IN WEB.CONFIG

 <connectionStrings>  
   <add name="ApplicationServices"  
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"  
      providerName="System.Data.SqlClient" />  
   
   <add name="connString" connectionString="data source=_______________;database=_________________________;Integrated Security=True" providerName="System.Data.SqlClient"/>  
  </connectionStrings>  
   


Creating necessary files:
1) Create a file named App_Code
2) Create a class file named CProfileManager.cs
3) Set build action of CProfileManager.cs to compile

Add the following name spaces in every code behind file that uses Sql, App_Code.
 using System.Data;  
 using System.Data.SqlClient;  
 using ProjectName.App_Code; -->Note: this calls out your App_Code files which is very important.   


UPLOADING & STORING

1: addprofilepic.aspx

Firstly, add these 3 codes in your add profile pic.aspx

 <asp:Label ID="lbladdprofilepic" Text="Add profile image: " runat="server" Width="300px"></asp:Label><br />  
   
 <asp:FileUpload ID="profilepicupload" runat="server" /><br />  
   
 <asp:Button ID="addbtn" Text="Add Profile Image" runat="server" Width="100px" onclick="addimagebtn_Click"></asp:Button>  
   


2: addprofilepic.aspx.cs

Next, in your code behind file, addprofilepic.aspx.cs

This code will be command the web browser to execute the "add" action when the button is clicked


 using System.Data;  
 using System.Data.SqlClient;  
 using System.Configuration;   

protected void addimagebtn_Click(object sender, EventArgs e)  
     {  
       int numOfRecordsAffected = 0;  
       CProfileManager ProfileManager= new CProfileManager();  
         
       byte[] collectedProfilePic = new byte[profilepicupload.PostedFile.ContentLength];  
       HttpPostedFile Image = profilepicupload.PostedFile;  
       Image.InputStream.Read(collectedProfilePic , 0, (int)profilepicupload.PostedFile.ContentLength);  
   
       if (profilepicupload.HasFile)  
       {  
         numOfRecordsAffected = ProfileManager.addProfileImage(collectedProfilePic);  
         Response.Redirect("Unknown.aspx");  
       }  
       else  
       {  
         numOfRecordsAffected = 0;  
       }  
     }  

3: CProfileManager.cs

In the class file, the configuration method must be called so that the browser can connect to the database.

 using System.Data;  
 using System.Data.SqlClient;  
 using System.Configuration;  

 public int addProfileImage(Byte[] inProfileImage)  
     {  
       int numOfRecordsAffected = 0;  
       SqlCommand cmd = new SqlCommand();  
       SqlConnection conn = new SqlConnection();  
       //Setup of the connection information   
   
       string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
       conn.ConnectionString = connString;  
   
       cmd.Connection = conn;  
       //Tell the Command object use the Connection object  
   
       //Prepare a INSERT SQL template - You have a Profile Database already  
       string sqlText = "INSERT INTO Profile (ProfileImage) ";  
       sqlText += " VALUES (@inProfileImage)";  
       //setup the SQL in the cmd object  
       cmd.CommandText = sqlText;  
   
       cmd.Parameters.Add("@inProfileImage", SqlDbType.Image, inProfileImage.Length);  
       cmd.Parameters["@inProfileImage"].Value = inProfileImage;  
   
       conn.Open();  
       numOfRecordsAffected = cmd.ExecuteNonQuery();  
       conn.Close();  
   
       return numOfRecordsAffected;  
     }  

RETRIEVING & DISPLAYING

So far, we have done the uploading of image, now we will display it

4: profileImageHandler.ashx.cs  -  Generic Handler

In this step, we are implementing an image based handler. For more information, you can check out this link here


using System.Data;
using System.Data.SqlClient;
using System.Configuration;   


 public void ProcessRequest(HttpContext context)  
     {  
       SqlConnection connection = new SqlConnection();  
       connection.ConnectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
       connection.Open();  
       string sql = "SELECT ProfileImage";  
       sql += " FROM Profile WHERE ProfileRecordId=@ProfileRecordId";  
       SqlCommand cmd = new SqlCommand(sql, connection);  
       cmd.Parameters.Add("@ProfileRecordId", SqlDbType.Int).Value = context.Request.QueryString["ProfileRecordId"];  
       cmd.Prepare();  
       SqlDataReader dr = cmd.ExecuteReader();  
       dr.Read();  
       context.Response.BinaryWrite((byte[])dr["ProfileImage"]);  
       dr.Close();  
       connection.Close();  
     }  

5: displayprofilepic.aspx

Simply place this line of code in the displayprofilepic.aspx to display the image.

 <asp:Image ID="profilepic" runat="server" width="100" Height="150"/>  

6: displayprofilepic.aspx.cs

In this step, do remember to insert the namespaces.

 protected void Page_Load(object sender, EventArgs e)  
     {  
       CProfileManager ProfileManager = new CProfileManager();  
       DataRow ProfileRow;  
       DataTable ProfileDataTable = new DataTable();  
       String ProfileRecordId = "";  
   
       if (Page.IsPostBack == false)  
       {  
         ProfileRecordId = (String)Request.QueryString["ProfileRecordId"];  
         ProfileDataTable = ProfileManager.displayOneProfileData(ProfileRecordId);  
         ProfileRow = ProfileDataTable.Rows[0];  
         profilepic.ImageUrl = "profileImageHandler.ashx?ProfileRecordId=" + ProfileRecordId;  
       }  
       }  

7: CProfileManager.cs - retrieve specific profile image only

 public DataTable displayOneProfileData(String inProfileRecordId)   
 {  
   SqlDataAdapter ad = new SqlDataAdapter();  
   SqlCommand cmd = new SqlCommand();  
   SqlConnection conn = new SqlConnection();  
   DataSet ds = new DataSet();  
   string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
   conn.ConnectionString = connString;  
   cmd.Connection = conn;  
   ad.SelectCommand = cmd;  
   conn.Open();  
   cmd.CommandText = "SELECT ProfileImage FROM Profile WHERE ProfileRecordId=@inProfileRecordId";  
   cmd.Parameters.AddWithValue("@inProfileRecordId", inProfileRecordId);  
   ad.Fill(ds, "ProfileData");  
   conn.Close();  
   return ds.Tables["ProfileData"];//Return the data table to the web form  
 }  


UPDATING

8: CProfileManager.cs - Update profile image

 public int updateOneProfile(String inProfileRecordId, Byte[] inProfileImage)  
 {  
   int numOfRecordsAffected = 0;  
   SqlCommand cmd = new SqlCommand();  
   SqlConnection conn = new SqlConnection();  
   string sqlText = "UPDATE Profile SET ProfileImage=@inProfileImage";  
   sqlText += " WHERE ProfileRecordId=@inProfileRecordId";  
   
   string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
   conn.ConnectionString = connString;  
   //setup the SQL in the cmd object  
   cmd.CommandText = sqlText;  
   cmd.Connection = conn;  
   
   cmd.Parameters.Add("@inProfileRecordId", SqlDbType.Int);  
   cmd.Parameters["@inProfileRecordId"].Value = inProfileRecordId;  
   
   cmd.Parameters.Add("@inProfileImage", SqlDbType.Image, inProfileImage.Length);  
   cmd.Parameters["@inProfileImage"].Value = inProfileImage;  
   
   conn.Open();  
   numOfRecordsAffected = cmd.ExecuteNonQuery();  
   conn.Close();  
   return numOfRecordsAffected;  
 } //for all fields updated  
   
   

9: updateProfile.aspx


 <b><asp:Label ID="lblupdateprofileimage" Text="Update profile image: " runat="server" Width="300px"></asp:Label></b>  
   <asp:Image ID="profileimagedisplay" runat="server" width="100" Height="150"/>  
   <asp:FileUpload ID="profilepicupload" runat="server" /><br />  
   
 <b><asp:Button ID="updateprofilebtn" Text="Update Profile" runat="server" Width="100px" onclick="updateprofilebtn_Click"></asp:Button></b><br />  
   


10: updateProfile.aspx.cs

 protected void Page_Load(object sender, EventArgs e)  
     {  
       CProfileManager ProfileManager = new CProfileManager();  
       DataRow ProfileRow;  
       DataTable ProfileDataTable = new DataTable();  
       String ProfileRecordId = "";  
   
       if (Page.IsPostBack == false)  
       {  
         ProfileRecordId = (String)Request.QueryString["ProfileRecordId"];  
         ProfileDataTable = ProfileManager.displayOneProfileData(ProfileRecordId);  
         ProfileRow = ProfileDataTable.Rows[0];  
         profileimagedisplay.ImageUrl = "profileImageHandler.ashx?ProfileRecordId=" + ProfileRecordId;  
       }  
     }  
   
     protected void updateprofilebtn_Click(object sender, EventArgs e)  
     {  
   
       int numOfRecordsAffected = 0;  
       CProfileManager ProfileManager = new CProfileManager();  
   
       string collectedProfileRecordId = (String)Request.QueryString["ProfileRecordId"];  
   
       if (profilepicupload.HasFile == true)  
       {  
         byte[] collectedProfilePic = new byte[profilepicupload.PostedFile.ContentLength];  
         HttpPostedFile Image = profilepicupload.PostedFile;  
         Image.InputStream.Read(collectedProfilePic, 0, (int)profilepicupload.PostedFile.ContentLength);  
         numOfRecordsAffected = ProfileManager.updateOneProfile(collectedProfileRecordId, collectedProfilePic);  
         Response.Redirect("Unknown.aspx");  
       }  
       else  
       {  
         numOfRecordsAffected = 0;  
       }  


MANAGING ALL IMAGES

11: manageprofilepics.aspx


 <div>  
   <table border="1">  
   <tr>  
    <td>Manage Profile Images</td>  
   </tr>  
   <tr>  
   <td><div id="div1" runat="server"></div></td>  
   </tr>  
   <tr>  
   <td>  
   <asp:GridView ID="grdData" runat="server" DataKeyNames="ProfileRecordId" AutoGenerateColumns="false" OnRowCommand="ProfileManage">  
    <Columns>  
   
   <asp:BoundField DataField="ProfileRecordId" HeaderText="Profile Id">  
   <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle"/>  
      <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />  
      </asp:BoundField>  
   
 <asp:TemplateField>  
  <ItemTemplate>  
   <asp:Image ID="profileimage" runat="server" ImageUrl='<%#"profileImageHandler.ashx?profileRecordId=" + Eval("profileRecordId")%>' width="100" Height="150"/>  
   
   
  </ItemTemplate>  
 </asp:TemplateField>  
   
   <asp:ButtonField ButtonType="Button" Text="Update" CommandName="UpdateOneProfileCommand"/>  
   </Columns>  
   </asp:GridView>  
   <div id="divMessage" runat="server"></div>  
   <asp:Button ID="addbtn" Text="Add" Width="70px" runat="server"   
       onclick="addbtn_Click"/>  
   </td>  
   </tr>  
   <tr>  
   <td style="text-align:right;">&nbsp;</td>  
   </tr>  
   </table>  
    
   </div>  

12: manageprofilepics.aspx.cs


 protected void Page_Load(object sender, EventArgs e)  
     {  
       if (Page.IsPostBack == false)  
       {  
         CProfileManager ProfileManager = new CProfileManager();  
         DataTable dtProfile = new DataTable();  
         dtProfile = ProfileManager.getAllProfileData();  
         grdData.DataSource = dtProfile;  
         grdData.DataBind();  
       }  
     }  
   
   
     public void ProfileManage(Object sender, GridViewCommandEventArgs e)  
     {  
   
       int intRowIndexWhichUserHasClicked = 0;  
       // If multiple buttons are used in a GridView control, use the  
       // CommandName property to determine which button was clicked.  
       if (e.CommandName == "UpdateOneProfileCommand")  
       {  
         intRowIndexWhichUserHasClicked = Convert.ToInt32(e.CommandArgument);  
         Response.Redirect("updateProfile.aspx?ProfileRecordId=" + grdData.DataKeys[intRowIndexWhichUserHasClicked].Value);  
       }  
     }  
   
   
   
     protected void addbtn_Click(object sender, EventArgs e)  
     {  
       Response.Redirect("addprofilepic.aspx");  
     }  

13: CProfileManager.cs - Retrieve all images


 public DataTable getAllProfileData()    
     {  
       SqlConnection conn = new SqlConnection();  
       SqlCommand cmd = new SqlCommand();  
       SqlDataAdapter ad = new SqlDataAdapter();  
       DataSet ds = new DataSet();  
   
       String sqlText = "SELECT ProfileRecordId, ProfileImage FROM Profile";  
       string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
       conn.ConnectionString = connString;  
       cmd.Connection = conn;  
       ad.SelectCommand = cmd;  
       cmd.CommandText = sqlText;  
       conn.Open();//open an active connection  
       ad.Fill(ds, "ProfileData");  
       conn.Close();//close the active connection   
       return ds.Tables["ProfileData"];  
     }  


ADDITIONAL:

To validate the type of image uploaded:


 <script type="text/javascript">  
   
   $(document).ready(function () {  
     $('#form1').validate({}); -->This is your form name (<form id="form1" runat="server">)  
   
     $("#profilepicupload").rules('add', {  
       required: true,  
       extension: "jpg|jpeg",  
       messages: {  
         required: "Please Upload Profile Image",  
         extension: "Please Upload only .jpg and .jpeg"  
       }  
     });  
   
   });  
   
 </script>  
   

We have come to the end to our tutorial :D Hope you can understand it :) If you do see any mistakes around, please tell me so that I can change it :)

No comments: