Prevent refresh after ajax file upload with ASP Generic Handler

1.5k Views Asked by At

I am trying to upload a file to the server without refreshing page on completion. I currently managed to solve the upload part using XMLHttpRequest to the Generic Handler (.ashx). However I cannot find the solution to prevent it from refreshing, tried using event.preventDefault() and return false; on the ajax but it doesn't work.

The ajax script

$('#uploadFileButton').on('click', function (event) {
    var counter;
    function UploadFile() {
        var files = $("#<%= file1.ClientID %>").get(0).files;
        counter = 0;
        // Loop through files
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var formdata = new FormData();
            formdata.append("file1", file);
            var ajax = new XMLHttpRequest();

            ajax.upload.addEventListener("progress", progressHandler, false);
            ajax.addEventListener("load", completeHandler, false);
            ajax.addEventListener("error", errorHandler, false);
            ajax.addEventListener("abort", abortHandler, false);
            ajax.open("POST", "FileUploadHandler.ashx");
            ajax.send(formdata);
        }
    }
    function progressHandler(event) {
        var percent = (event.loaded / event.total) * 100;
        $("#progress").html(Math.round(percent) + "% uploaded... please wait");
    }
    function completeHandler(event) {
        counter++
        $("#progress").html(counter + " " + event.target.responseText);
    }
    function errorHandler(event) {
        $("#progress").html("Upload Failed");
    } function abortHandler(event) {
        $("#progress").html("Upload Aborted");
    }
});

The FileUploadHandler.ashx

public class FileUploadHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        HttpPostedFile file = context.Request.Files[0];
        string fname = context.Server.MapPath("~/Document/" + file.FileName);
        file.SaveAs(fname);
        context.Response.ContentType = "text/plain";
        context.Response.Write("File Uploaded Successfully!");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

And in case you need it, the index.aspx body

<body>
    <form id="form1" runat="server">
        <asp:FileUpload ID="file1" runat="server" AllowMultiple="true"/>
        <button id="uploadFileButton">Upload</button>
        <div id="progress">
        </div>
    </form>
</body>

Anyone care to shed light on how to solve this?

2

There are 2 best solutions below

4
RGS On BEST ANSWER

Use event.preventDetault() inside button click event. You have to call UploadFile() function inside button click event.

<script type="text/javascript">
  $(document).ready(function (e) {
      $('#uploadFileButton').click(function (event) {
          var counter;
          UploadFile();
          event.preventDefault();
      });
      function UploadFile() {
        var files = $("#<%= file1.ClientID %>").get(0).files;
        counter = 0;
        // Loop through files
        for (var i = 0; i < files.length; i++) {
           var file = files[i];
           var formdata = new FormData();
           formdata.append("file1", file);
           var ajax = new XMLHttpRequest();
           ajax.upload.addEventListener("progress", progressHandler, false);
           ajax.addEventListener("load", completeHandler, false);
           ajax.addEventListener("error", errorHandler, false);
           ajax.addEventListener("abort", abortHandler, false);
           ajax.open("POST", "Handler.ashx");
           ajax.send(formdata);
         }
      }
      function progressHandler(event) {
         var percent = (event.loaded / event.total) * 100;
         $("#progress").html(Math.round(percent) + "% uploaded... please wait");
      }
      function completeHandler(event) {
        counter++
        $("#progress").html(counter + " " + event.target.responseText);
      }
      function errorHandler(event) {
        $("#progress").html("Upload Failed");
      } 
      function abortHandler(event) {
        $("#progress").html("Upload Aborted");
      }
  });
</script>

enter image description here

0
Dan On

GOT IT! Its actually the VS2017's "Enable Reload on Save" property is set to True which is the default. I followed the solution here , found it after googled "SaveAs refresh page". @RGS code IS RIGHT, its just my VS settings. Hope this helps others.