Wakam Fx
Wakam Fx

Reputation: 367

ASP.Net Core File Upload Progress Session

I'm writing a file upload in ASP.Net Core and I'm trying to update a progress bar but when the Progress action is called from javascript, the session value isn't updated properly.

The progress is saved in the user Session using:

public static void StoreInt(ISession session, string key, int value)
{
    session.SetInt32(key, value);
}

The upload:

$.ajax(
  {
      url: "/Upload",
      data: formData,
      processData: false,
      contentType: false,
      type: "POST",
      success: function (data) {
          clearInterval(intervalId);
          $("#progress").hide();
          $("#upload-status").show();
      }
  }
);

Getting the progress value:

intervalId = setInterval(
  function () {
      $.post(
        "/Upload/Progress",
        function (progress) {
            $(".progress-bar").css("width", progress + "%").attr("aria-valuenow", progress);
            $(".progress-bar").html(progress + "%");
        }
      );
  },
  1000
);

Upload Action:

[HttpPost]
public async Task<IActionResult> Index(IList<IFormFile> files)
{
    SetProgress(HttpContext.Session, 0);
    [...]

    foreach (IFormFile file in files)
    {
        [...]
        int progress = (int)((float)totalReadBytes / (float)totalBytes * 100.0);
        SetProgress(HttpContext.Session, progress);
        // GetProgress(HttpContext.Session) returns the correct value
    }

    return Content("success");
}

Progress Action:

[HttpPost]
public ActionResult Progress()
{
    int progress = GetProgress(HttpContext.Session);
    // GetProgress doesn't return the correct value: 0 when uploading the first file, a random value (0-100) when uploading any other file

    return Content(progress.ToString());
}

Upvotes: 3

Views: 9109

Answers (1)

Wakam Fx
Wakam Fx

Reputation: 367

Alright, I used the solution suggested by @FarzinKanzi which is processing the progress client side instead of server side using XMLHttpRequest:

$.ajax(
  {
      url: "/Upload",
      data: formData,
      processData: false,
      contentType: false,
      type: "POST",
      xhr: function () {
          var xhr = new window.XMLHttpRequest();
          xhr.upload.addEventListener("progress", function (evt) {
              if (evt.lengthComputable) {
                  var progress = Math.round((evt.loaded / evt.total) * 100);
                  $(".progress-bar").css("width", progress + "%").attr("aria-valuenow", progress);
                  $(".progress-bar").html(progress + "%");
              }
          }, false);
          return xhr;
      },
      success: function (data) {
          $("#progress").hide();
          $("#upload-status").show();
      }
  }
);

Thank you for your help.

Upvotes: 15

Related Questions