I am using System.Drawing in ASP.NET to generate a custom image based on what a user enters within a form. This image once generated will be saved in a directory on the server.
What I would like to happen is to display a loading icon on a separate page (after the user has submitted the form) and once the custom image is generated, the loading icon will be replaced with the image from the server directory.
Some of you may suggest that I use a Generic Handler (.ashx) to show the image as a JPEG within a <img />
tag. But the problem I have with this is that if the user right-clicks over the image to save, it will be saved as a .ashx file.
The problem I am having is not knowing how to refresh the page once the image has successfully been created in the file directory.
There are quite a few different ways you could achieve this, but here's what I'd personally do. First, I'd create my handler to receive the form submissions (the data you're using to generate the image) which will generate the image (I wouldn't save the file to the server personally, but it's easy enough to do if you wish) and encode it to base64, using my handler to return this string using JSON.
public void ProcessRequest (HttpContext context)
{
// generate the image from POST / GET data sent to this handler from your form
Bitmap bmp = GenerateImage(postData);
// now convert your generated image to a base64 string
string base64 = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Png);
base64 = Convert.ToBase64String(ms);
}
// now return this base64 string to the caller
context.Response.ContentType = "application/json";
string json = "{ \"imageBase64\": \"" + base64 + "\" }";
context.Response.Write(json);
}
At the client side I would be using jQuery and make an Ajax call to my handler to POST/GET up the form data and retrieve the base64 encoded image's string to then set the src
property of my img
html tag.
function postAndRetrieveImage() {
$.ajax({
url: "http://server/myhandler.ashx",
data: jsonDataParsedFromForm,
dataType: "json",
type: "POST",
contentType: "application/json",
async: true,
cache: false,
beforeSend: function() {
// overlay your "loading..." image or something while you wait
// for response from the server
},
complete: function() {
// hide your "loading..." image (or whatever it is) as the operation
// has completed
},
success: function(data) {
var response = jQuery.parseJSON(data.d);
// set the src attribute of the IMG tag (prefixed with the usual
// image stuff) with the base64
var image = document.getElementById("myImage");
image.setAttribute("src", "data:image/png;base64," + response.imageBase64);
},
error: function() {
// display error in some way
}
});
}
Like I said, there are MANY ways you could achieve this so this ROUGH (untested) example is one of the ways I'd do this. Having the IMG
tag should allow them to right-click save the image also.
Hope this helps as a starting point.