How to Upload file asynchronously using generic handler

I've used the code bellow to upload a file to server asynchronously:

HTML:

<form id="file_upload" action="UploadFile.ashx" target="upload-target" method="post" enctype="multipart/form-data" onsubmit="javascript:return uploadClicked();">

    <input type="file" id="newFile" name="newFile" />

    <input type="submit" />

    <iframe id="upload-target" name="upload-target"></iframe>

</form>

After the submit button clicked, the function uploadClicked() will be fired:

function uploadClicked() {
    if (condition == true)
        return true; //the form will submit
    else
        return false;
}

Now the generic handler UploadFile.ashx will save the file and return the result:

if (context.Request.Files.Count > 0)
{
    context.Request.Files["newFile"].SaveAs(HttpContext.Current.Server.MapPath("/Images/myFile.png"));
    response.Write("DONE");
}
else
{
    response.Write("FAILED");
}

This works well and the result will be showing in the iframe tag.

Is there anyway to get the result ("DONE" or "FAILED") in client-side like this ?

function uploadFinished()
{
     if ( response == "DONE" )
     {
          // show the result
     }
     else
     {
          // show error
     }
}

Please help me doing this without using JQuery.

Thanks in advance.

Last updated:1/15/2015 10:24:41 PM

1 Answers

Royce Roy
Royce Roy

You could use the XHR2 FormData object to upload the file to the server asynchronously and retrieve the response from the server handler:

function uploadClicked() {
    var fd = new FormData();
    var file =document.getElementById('newFile');
    fd.append(file.name, file.files[0]);
 
    var xhr = new XMLHttpRequest();
    var form =document.getElementById('file_upload');
    xhr.open(form.method,form.action);
    xhr.onreadystatechange = function () {
        if (xhr.readyState== 4 && xhr.status == 200) {
            //xhr.responseText will contain the response from the server
            alert(xhr.responseText);
        }
    };
    xhr.send(fd);
 
    // We are submitting the form asynchronously
    return false;
}

Answer