Implementation: ajax post - upload files + upload.onprogress using FormData

I am trying to implement an updated Ajax.post

using javascript FormDataI sent files to a dedicated controller and successfully saved it to the file system.

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

target:

send / send files (possibly one by one), so I can evaluate each and apply ETA to the client.

this is my ajax (standard for downloading files using the above 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(){
    }
 });

the call is still successful 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 looked and tried many code examples adding ajax  xhr.upload.onprogress

adding to the signature above one other 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.
                        }
               };
    },

, , , , 100 ...

, , .

+4

All Articles