Introduction
Many times we come across the process of uploading and retrieving images using database. For a experienced developer it will not be a big problem. But for beginers, it is. So in this article we see how to upload an image to database and retrieve it from database.
For this a Generic Handler is used. You might get a doubt that what is the relation between uploading images and a generic handler. Here is the answer.
A Generic Handler is the process that runs in response to a request made to a asp.net webapplication. All .aspx pages are processed by Asp.Net Page handler. When users request an .aspx file, the request is processed by the page through the page handler. One can create thier own handler that render custom output to the browser.
An HTTP module is an assembly that is called on every request that is made to a web application. All HTTP modules will examine incoming and outgoing requests and take action based on the request.
We will see all about HTTP handlers and modules in another article.
When to use a HTTP Handler ?
There are different types of handlers like Asp.Net page handler, Web service handler, Generic web handler and Trace handler. A Generic Web Handler is the default HTTP handler for all Web handlers that do not have a UI and that include the @ WebHandler directive..It is used in the following typical cases.
- Image Server
- Rss Feed
An image produced by a generic handler can be bind to a verity of Asp.Net data controls like gridview, datalist, repeater or listview. Here it is explained with a Listview.
The code shown below is used to store and retrieve the images. Follow the steps as mentioned below.
- Create a New Website. Copy and paste the code from first two Tabs into respective pages.
- Create a App_code Directory. In that create a Class file with name 'DataAceess'. Now copy and paste the code from third Tab into this class file.
- Now take a new Generic Handler Template and paste the code from Thumbnail.ashx Tab.
- Finally create a database 'ImageStore' in sql server and run the script given in the source code. If you are not a registerd user please register to down load the complete application.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%--Example by codemyne--%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Image Upload/Retrieve using DB</title> </head> <body style="font-family: Verdana; font-size: 10pt"> <div style="padding: 10px"> <form id="form1" runat="server"> <div><asp:FileUpload ID="fileUpload" runat="server" style="width: 350px"/><br /></div> <p><asp:Button ID="Submit" runat="server" Text="Upload" onclick="Submit_Click" /></p> <p /> <p /> <div>Images Retrieved from Database<br /><br /></div> <div> <asp:ListView runat="server" ID="ListView1" GroupItemCount="4" > <LayoutTemplate> <table runat="server" id="table1"> <tr runat="server" id="groupPlaceholder"> </tr> </table> </LayoutTemplate> <GroupTemplate> <tr runat="server" id="tableRow"> <td runat="server" id="itemPlaceholder" /> </tr> </GroupTemplate> <ItemTemplate> <td id="Td1" runat="server" valign="bottom"> <div><asp:Image ID="imageThumb" runat="server" ImageUrl='<%#"Thumbnail.ashx?id=" + Eval("ID") %>' Height="45" Width="45" /></div> </td> </ItemTemplate> </asp:ListView> </div> </form> </div> </body> </html>
using System; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ListView1.DataSource = DataAccess.ListImages(); DataBind(); } } protected void Submit_Click(object sender, EventArgs e) { if (IsPostBack) HandleUploadedFile(); } private void HandleUploadedFile() { // get the file instance HttpPostedFile fi = Request.Files.Get(0); // create a byte array to store the file bytes byte[] fileBytes = new byte[fi.ContentLength]; // fill the byte array using (System.IO.Stream stream = fi.InputStream) { stream.Read(fileBytes, 0, fi.ContentLength); } // insert the image DataAccess.InsertImage( fileBytes); // bind the image list ListView1.DataSource = DataAccess.ListImages(); DataBind(); // clean up fileBytes = null; } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Web; public class DataAccess { public DataAccess() { } public static byte[] GetImageByID(int ImageID) { string cnn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; using (SqlConnection connection = new SqlConnection(cnn)) { using (SqlCommand command = new SqlCommand("dbo.up_GetImageByID", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("@ ID", ImageID)); connection.Open(); object result = command.ExecuteScalar(); try { return (byte[])result; } catch { return null; } } } } public static void InsertImage(byte[] imageAsBytes) { string cnn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; using (SqlConnection connection = new SqlConnection(cnn)) { using (SqlCommand command = new SqlCommand("dbo.up_InsertImage", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("@ imageAsBytes", imageAsBytes)); connection.Open(); command.ExecuteNonQuery(); } } } public static List<ImageData> ListImages() { string cnn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; using (SqlConnection connection = new SqlConnection(cnn)) { using (SqlCommand command = new SqlCommand("dbo.up_ListImages", connection)) { command.CommandType = CommandType.StoredProcedure; connection.Open(); List<ImageData> list = new List<ImageData>(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ImageData item = new ImageData() { ID = (int)reader["ID"] }; list.Add(item); } } return list; } } } public class ImageData { public int ID { get; set; } public ImageData() { } } }
<%@ WebHandler Language="C#" Class="Thumbnail" %> using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Web; public class Thumbnail : IHttpHandler { public void ProcessRequest (HttpContext context) { // Set up the response settings context.Response.ContentType = "image/jpeg"; context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.BufferOutput = false; if (!string.IsNullOrEmpty(context.Request.QueryString["ID"])) { // get the id for the image int id = Convert.ToInt32(context.Request.QueryString["ID"]); // get the image as a byte array byte[] imageAsBytes = DataAccess.GetImageByID(id); // put the byte array into a stream Stream stream = new MemoryStream((byte[])imageAsBytes); // setup the chunking of the image data (good for large images) int buffersize = 1024 * 16; byte[] buffer = new byte[buffersize]; // push the bytes to the output stream in chunks int count = stream.Read(buffer, 0, buffersize); while (count > 0) { context.Response.OutputStream.Write(buffer, 0, count); count = stream.Read(buffer, 0, buffersize); } } } public bool IsReusable { get { return true; } } }
Happy coding.!
Comments Post a Comment