Resources » Code Snippets » ASP.NET WebForms

Image preview before uploading using AsynFileUpload


Updated: Category: ASP.NET WebForms
Author: Member Level: SilverPoints: 2


This article shows how to preview the image before uploading the image using to the server so that it can be saved into the database later. User will always like to see the image which has to be uploaded. This has been done using AsyncFileUpload(Ajax Control Toolkit) and HTTPHandler.



It is always nice to show the preview of the image which has to be uploaded by the user.

After lot of searching I found that the HTML upload i.e input type="file"... is not useful as it does not expose enough server side events. For this scenario the better control is Ajax control ToolKit's AjaxFileUpload, which has enough server side events and client side events.

After the file is uploaded instead of saving it in the location in the server instead HttpHandler can be used which can write the uploaded image directly into the response. so no storage and less headaches.

What have been done.

1) Use AjaxFileUpload to upload the file.
2) Store the file in the session object.
3) Use the session object in the Handler. Set the Image control source to the Handler.


In .aspx.cs

public static readonly string STORED_IMAGE = "SessionImage";

protected void OnAsyncFileUploadComplete(object sender, AsyncFileUploadEventArgs e)
{
if (asyncFileUpload.PostedFile != null)
{
HttpPostedFile file = asyncFileUpload.PostedFile;

byte[] data = ReadFile(file);
//Store the image in the session.
Session[STORED_IMAGE] = data;
}
}


private byte[] ReadFile(HttpPostedFile file)
{
byte[] data = new Byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
return data;
}


In .aspx

Note: Use the randomnumber in the querystring of the handler otherwise, browser caches the first image and returns the same image again and again.


<script language="javascript" type="text/javascript">
function getRandomNumber() {
var randomnumber = Math.random(10000);
return randomnumber;
}

function OnClientAsyncFileUploadComplete(sender, args)
{
var handlerPage = '<%= Page.ResolveClientUrl("~/ImageHandler.ashx")%>';
var queryString = '?randomno=' + getRandomNumber();
var src = handlerPage + queryString;
var clientId = '<%=previewImage.ClientID %>';
document.getElementById(clientId).setAttribute("src", src);
}
</script>


The Handler

Note use the IRequiresSessionState to access the session variables in the Handler.



public class ImageRequestHandler: IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();

if(context.Request.QueryString.Count != 0)
{
//Get the stored image and write in the response.
var storedImage = context.Session[_Default.STORED_IMAGE] as byte[];
if (storedImage != null)
{
Image image = GetImage(storedImage);
if (image != null)
{
context.Response.ContentType = "image/jpeg";
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
}

private Image GetImage(byte[] storedImage)
{
var stream = new MemoryStream(storedImage);
return Image.FromStream(stream);
}

public bool IsReusable
{
get { return false; }
}
}


In web.config


<add validate="false" verb="*" path="ImageHandler.ashx"type="ImagePreviewDemo.ImageRequestHandler,ImagePreviewDemo"/>



Please find the full source code attached.


Did you like this resource? Share it with your friends and show your love!

Responses to "Image preview before uploading using AsynFileUpload"
Author: Anibal Díaz  26 Aug 2011   Member Level: Bronze   Points : 1
Hello,

I have a problem.
I have 1 page and 1 user control... this user control have asyncfileupload control.

the event code OnAsyncFileUploadComplete is ok, but the page is not refreshed with the image into the avatar...

the called to handler 'ashx' is not ok.

my code into the event Page_Load:

method Avatar.Page_Load(sender: Object; e: EventArgs);
begin
if Not IsPostBack then
previewImage.ImageUrl := '~/Images/MyImage.jpg'
else
previewImage.ImageUrl := Self.Parent.ResolveClientUrl("~/AvatarHandler.ashx?fichero=stream");
end;


help me please!
thanks



Guest Author: Seda   20 Feb 2012
many people do not know if the word in the image is an important thing. That influence is also to help your site or blog search engines indexed selfish recently posted..


Guest Author: Eric   03 Aug 2012
You are awesome! Works great. One thing about the article, the web.config section needs some HTML encoding done on the less than and greater than signs ( can't see the contents without going to View Source ).


Author: Tony John  04 Aug 2012   Member Level: Gold   Points : 0
Eric,

Thanks for the comment. We have fixed the issue with encoding.



Guest Author: Resonance   08 Jan 2013
Hello, how I can set the displayed image size in IE? In FF and other browsers work just sizing ASP: Image, but for some reason IE ignores the settings and displays the full-size image


Guest Author: shyam sharma   04 Mar 2013
Thanks $ the help. It works and i m so thankful.


Author: Deepak  29 Mar 2014   Member Level: Bronze   Points : 0
can i get download link as i m getting the error in handler


Author: Atul Sharma  09 May 2014   Member Level: Silver   Points : 0
Hi, I am looking for view image before saving image in database so please advise to me how to do that?
if possible to provide code of important link so please provide it soon.



Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index
    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John
     
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India

    
    
    
    

    Click the "Follow" button above to follow Tony John