【问题标题】:ASP.Net Core File Upload Progress SessionASP.Net Core 文件上传进度会话
【发布时间】:2017-02-10 16:38:59
【问题描述】:

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

进度保存在用户会话中使用:

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

【问题讨论】:

  • 你在本地测试这个,你上传的文件长度是多少?
  • 我在本地和远程服务器上都试过了,都失败了。我还尝试了单个/多个小/大文件。在这里,我创建了一个解决方案来重现该问题:github.com/Fxbouffant/FileUploadCore 在文件仍在上传时,进度操作始终返回 0。然后上传文件时返回100,中间没有值。
  • 检查进度的间隔为1秒。是不是在检查进程之前下载就结束了?
  • 这不是上传进度的好方法。而且不会一帆风顺。我通过 xmlHttpRequest 创建实时连接,但它是 asp.net 而不是 mvc。你想要吗?
  • 谢谢,太完美了。我使用 xhr 事件来更新进度。

标签: c# jquery asp.net-core


【解决方案1】:

好的,我使用了@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();
      }
  }
);

感谢您的帮助。

【讨论】:

  • 抱歉,我没有足够的代表来支持您的 cmets:/
  • 别担心兄弟。
猜你喜欢
  • 2018-02-22
  • 2013-01-04
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 2021-08-02
相关资源
最近更新 更多