dotnetspider.com
Login Login    Register      

TutorialsForumCareer DevelopmentResourcesReviewsJobsInterviewCommunitiesProjectsTraining

Subscribe to Subscribers
Talk to Webmaster
Tony John

Facebook
Google+
Twitter
LinkedIn
Online Membersbaskar
More...
Join our online Google+ community for Bloggers, Content Writers and Webmasters




Resources » Code Snippets » ASP.NET WebForms

Image preview before uploading using AsynFileUpload


Posted Date:     Category: ASP.NET WebForms    
Author: Member Level: Silver    Points: 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.

Attachments
  • ImagePreviewUploadDemo (40858-835-ImagePreviewDemo.rar)





  • 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 2011Member 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: 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 2012Member 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


    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.


    Next Resource: Clear All text box contents in a web form
    Previous Resource: Enable and disable textbox on checkbox check
    Return to Resources
    Post New Resource
    Category: ASP.NET WebForms


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    Preview Image AsyncFileUpload Handler  .  



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds


    About Us    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.