ASP.Net核心文件上传进度会议 [英] ASP.Net Core File Upload Progress Session

查看:64
本文介绍了ASP.Net核心文件上传进度会议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ASP.Net Core中编写文件上传,并且尝试更新进度条,但是当从javascript调用Progress操作时,会话值未正确更新.

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);
}

上传:

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

获取进度值:

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

上传操作:

[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");
}

进度动作:

[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());
}

推荐答案

好吧,我使用了@FarzinKanzi建议的解决方案,该解决方案使用XMLHttpRequest处理进度客户端而不是服务器端:

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();
      }
  }
);

谢谢您的帮助.

这篇关于ASP.Net核心文件上传进度会议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆