Image upload and previewing is a very basic requirement usually when we come across user registration page or add and edit an institution, etc. In this post I am providing here the sample which does the same using ASP.NET Ajax.
I had given here just a simple example just to upload and preview the image, I am not going to save the image in the Database or Load from the Database, but of course you can extend this control based on your requirements.
This is how the final screen will look once you complete the code:
You will need Ajax Control Toolkit for AsyncFileUpload control, this controls helps to perform the asynchronous operation without page refresh. Best way to get this through NuGet package manager in you project.
Now lets see the ASP.NET Page and the Code Behind for that.
The code above is very simple and self explanatory, still let me quickly give you a walkthrough. In the Script section of this page I am writing an function which gets called by the AsyncFileUpload control once the file upload to server is completed. Basically in Server side we are just saving the image temporarily in Session which is referenced in Handler section which I am going to cover very soon. In the same function we are calling the ImageHandler which gets the image from the session as mentioned above and write the image to response stream. Once the operation is over this function maps the source to the image control in the client side.
While calling the Image Handler sometimes in certain cases the browser caches the response stream due to which we may face the problem in refreshing the images. To overcome this you can see In the same script I have used a function to generate a random number which basically used to get the unique URL to call the ImageHandler and overcome the response caching issue.
I have almost explained the entire functionality still lets look into the ImagePreviewHandler and Code Behind part of the application.
In the first snippet I have given the code behind of the ASP.NET page, which simple saves the image byte array into the Session in the OnUploadedComplete event of AsyncFileUpload control. This image byte array is used later in Image Handler to process further.
And finally in the second snippet I am showing the ASP.NET Generic Handler, in ProcessRequest I am fetching the image byte array from the Session and writing the image to the response of the page. A part from implementing IHttpHandler, I am also deriving the System.Web.SessionState.IRequiresSessionState, which provides me the ability to read and write to the session. This is very important in our case since we are using session variable to read the images in the Image Request Handler.
And that all we need. You can download the code from here.