HOW TO UPLOAD FILE ASYNCHRONOUSLY USING GENERIC HANDLER

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
 1130  View(s)
Ratings:
Rate this:

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.

  1. Royce Roy

    Post:149

    Points:1043
    Re: How to Upload file asynchronously using generic handler

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!