.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Show Uploaded Image in Image Control in Asp.net

Posted By:Shweta Kulkarni       Posted Date: September 16, 2009    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  
 

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.

Thanks
Shweta Kulkarni MCTS

 Subscribe to Articles

     

Further Readings:

Responses
Author: viv1         Company URL: http://www.dotnetspark.com
Posted Date: February 23, 2010

Very helpful article....But how to vary the size of the image.
thanks ....

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend