我正在编写一个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());
}
xmlHttpRequest
创建一个实时连接来完成此操作,但它是基于asp.net而非MVC。您需要吗? - Farzin Kanzi