Ope*_* Fx 1 c# jquery asp.net-core
我正在 ASP.Net Core 中编写文件上传,我正在尝试更新进度条,但是当从 javascript 调用 Progress 操作时,会话值未正确更新。
使用以下方法将进度保存在用户会话中:
public static void StoreInt(ISession session, string key, int value)
{
session.SetInt32(key, value);
}
Run Code Online (Sandbox Code Playgroud)
上传:
$.ajax(
{
url: "/Upload",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
clearInterval(intervalId);
$("#progress").hide();
$("#upload-status").show();
}
}
);
Run Code Online (Sandbox Code Playgroud)
获取进度值:
intervalId = setInterval(
function () {
$.post(
"/Upload/Progress",
function (progress) {
$(".progress-bar").css("width", progress + "%").attr("aria-valuenow", progress);
$(".progress-bar").html(progress + "%");
}
);
},
1000
);
Run Code Online (Sandbox Code Playgroud)
上传动作:
[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");
}
Run Code Online (Sandbox Code Playgroud)
进展行动:
[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());
}
Run Code Online (Sandbox Code Playgroud)
Ope*_* Fx 11
好吧,我使用了@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();
}
}
);
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助。