ASP.Net Core文件上传进度会话

3

我正在编写一个ASP.Net Core的文件上传功能,我试图更新进度条,但是当从javascript调用Progress操作时,会话值没有正确更新。

进度通过用户会话(Session)保存:

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

你在本地测试过吗?上传的文件长度是多少? - Farzin Kanzi
我在本地和远程服务器上都尝试过,但都失败了。我还尝试使用单个/多个小/大文件。 这里我创建了一个解决方案来重现此问题: https://github.com/Fxbouffant/FileUploadCore进度操作始终返回0,而文件仍在上传。然后在文件上传时返回100,没有其他值。 - Wakam Fx
1
检查进度的时间间隔为1秒。难道不可能在检查进度之前就下载完成了吗? - Farzin Kanzi
3
这不是一种好的上传进度方式,可能无法顺利进行。我使用xmlHttpRequest创建一个实时连接来完成此操作,但它是基于asp.net而非MVC。您需要吗? - Farzin Kanzi
谢谢,太棒了。我使用xhr事件来更新进度。 - Wakam Fx
1个回答

15

好的,我使用了@FarzinKanzi提出的解决方案,该方案是使用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();
      }
  }
);

感谢您的帮助。


抱歉,我没有足够的声望来点赞你的评论 :/ - Wakam Fx
2
不用担心,兄弟。 - Farzin Kanzi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接