Earlier today I posted a blog about using a generic handler (.ashx) to upload a file to a web server, and in the back of my head I wanted to use it somewhere neat and special, and I also want to find the most reliable and working version. And I also want to learn what the approaches are to doing so, and why not to do it a certain way, etc.
So back to the topic of the post and the first thing that needs to be understood is that you CANNOT upload files with AJAX/JavaScript. This is because of you cannot retrieve the contents of a file off a local system, and if this was so it would cause major security headaches. So what I ended up doing is following the IFRAME approach, by which you make it look as if the upload is happening all AJAX-like when in actual fact its not. So what I did was create an IFRAME:
Notice that I added a div called divTimerValue, which I use to display some progress indicator, in my case it will be busy that will grow and subside with dots. In the source file (where the IFRAME points to) I create a form:
Notice that it has the ReturnValue.ashx action and that I have added an onclick function to the submit button, which looks like this:
function dotsAnimate() {
parent.document.getElementById("divFrame").style.display = 'none';
var dotspan = parent.document.getElementById("divTimerValue");
dotspan.style.display = '';
setInterval(function() {
if (dotspan.innerHTML == 'busy...') {
dotspan.innerHTML = 'busy.';
}
else {
dotspan.innerHTML += '.';
}
}, 1000);
};
The dotsAnimate function uses the setTimeout function to create the animation. The generic handler then returns some HTML that contains a javascript function that clears the timeout and prints a message in the divTimerValue div:
context.Response.Write(@"");
context.Response.Write(savedFileName);
And this code produces the desired result.