Thursday, August 13, 2009

Show Uploaded Image in Image Control in Asp.net

Background:

Many a times we come across with the requirement to show uploaded file information in Grid View or in some other control or display uploaded image file in Image control. There is various way of doing it you can either do this on client side or do it on server side. You can either create physical folder to store file or in a database or store it in stream, should always choose better option.

Introduction

In this article I am focusing on generating image on server side by converting posted file content in binary format, then storing it in session so that it can be accessed in Image.aspx for generating image.

Below are steps to execute in order to generate expected output.

1. Create a form with Image control, File Upload control and Upload Button (Sample.aspx)

2. Create another form called Image.aspx which will generate uploaded Image and display it in image control.(Image.aspx)

3. On Click of Upload button write following code.(Sample.aspx)

protected void btnUpload_Click(object sender, EventArgs e)

{

string imgFileName ="";//variable to store image file name.

//Below checking wehter user has selected image file or not.

if (FileuploadControl1.FileName.Length == 0)

{

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "Message1", "alert('Provide Image File')", true);

return;//If no file is selected by user then show appropriate message with the help of javascript.I have used Ajax ScriptManager for this.

}

else

{

imgFileName = FileuploadControl1.FileName;//storing image file name.

if ((System.IO.Path.GetExtension(imgFileName) == ".jpg") || (System.IO.Path.GetExtension(imgFileName) == ".jpeg") || (System.IO.Path.GetExtension(imgFileName) == ".bmp") || (System.IO.Path.GetExtension(imgFileName) == ".gif") || (System.IO.Path.GetExtension(imgFileName) == ".ico") || (System.IO.Path.GetExtension(imgFileName) == ".png"))

{ //Checking for image file extensions.

byte []img;//To store image file

//HttpPostedFile class belong to System.web namespace provide access to the files uploaded by users

HttpPostedFile postFile = FileuploadControl1.PostedFile;

//stores upladed file information

int contentLength = postFile.ContentLength;//Storing file length

img = new byte[contentLength];//Initializing byte variable by passing image content length.

postFile.InputStream.Read(img, 0, contentLength); //Reading byte content

DataTable dtTemp = new DataTable("TempImage");//Creating temprory data table which will store image information

dtTemp.Columns.Add("Image",System.Type.GetType("System.Byte[]"));//Byte Image column

DataRow dr = dtTemp.NewRow();

dr[0] = img;//storing binary image information in table.

dtTemp.Rows.Add(dr);

Session["dt"] = dtTemp;//storing temprory table in seesion.

ImageControl.ImageUrl = "Image.aspx?id=0"; //Query string id we have passed

in order to generate new request everytime.

}

else

{

//If user has selected file other than image then show appropriate java script message.

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "Message2", "alert('Provide only Image File'", true);

return;

}

}

After writing above code in Sample.aspx we will write some snippet in Image.aspx which will generate uploaded image.

Image.aspx

protected void Page_Load(object sender, EventArgs e)

{

//On Page Load we are reading data stored in session.

DataTable dt = new DataTable();

dt = (DataTable)Session["dt"];

byte[] b = null;

int id =Convert.ToInt16(Request.QueryString["id"]); //Fetching query string Id.

If(dt.Rows.Count > 0)

{

//storing image binary information in byte array variable.

b = ((byte[])dt.Rows[0][“Image”]);

}

if (b != null)

{

//setting content type.

Response.ContentType = "image/jpeg";

//writes binary array with binary write

Response.BinaryWrite(b);

}

Summary:

Here we have looked how to generate image uploaded from fileupload control we have used Response.BinaryWrite() Method for this you can also use Response.OutputStream.Write (b, 0, b.Length) for generating image.
 

No comments: