implementation of: ajax post - upload files + upload.onprogress using FormData

Viewed 222

i am trying to implement an upgraded Ajax.post

using javascript FormData i have posted files to dedicated Controller and successfully saved it to file system.

so i have a controller - "UploadFiles" with standard use of Request.Files that "under the hood" i think you might say, it processes the files.

the goal is :

to send/post files , (maybe one by one) so i could estimate each and plot the ETA to client.

this is my ajax (a standard for file upload using the above mentioned approach) so far.

Log("AajaxNoPostBack preparing post-> " + targetUrl);
$.ajax({
    type: 'POST',
    url: targetUrl,
    contentType: false,//two lines for posting a file i guess
    processData: false,
    data: FormDataobj,
    success : function forsuccess(){
    },
    error : function forerr(){
    }
 });

so far it is being implemented successfully calling MVC4 controller

 [HttpPost]
 public JsonResult UploadFiles()
 {
     HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;

     foreach (string file in Request.Files)
     {
         // Checking for Internet Explorer  
         if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
         {
             string[] testfiles = hpf.FileName.Split(new char[] { '\\' });
             name = testfiles[testfiles.Length - 1];
         }
         else
         {
             fname = hpf.FileName;
         }
     }
     fname = System.IO.Path.Combine(Server.MapPath("~/Content/uploaded"), fname);
     hpf.SaveAs(fname);  

     //the above is within try/catch
      return Json(new
      {
          Name = "TESTRespJObj",
          File = "file",
          Length = 111,
          Type = "SomeType",
          err = "noErr"
       });
 }

i have looked and tried many code examples adding the ajax xhr.upload.onprogress

adding to the signature above one more property / option

 xhr: function () {
               var xhr = new window.XMLHttpRequest();
               xhr.upload.onprogress = updateProgress;
               xhr.addEventListener("load", transferComplete, false);
               xhr.addEventListener("error", transferFailed, false);
               xhr.addEventListener("abort", transferCanceled, false);
               xhr.open("POST", targetUrl, true);
               xhr.onreadystatechange = function () {
                   if (xhr.readyState == 4 && xhr.status == 200) {
                       alert(xhr.responseText); // handle response.
                        }
               };
    },

and off course plenty of code implementing event handlers i did not wish to flud this post with unnecessary extra 100 lines...

as you can think and see above i am desperately trying to mix scripts from couple of code samples i know nothing about and have zero experience with .

any help will be appriciated

0 Answers
Related