本文提供完整前端程式碼,示範如何在 ASP.NET MVC 中結合 HTML5、jQuery 實作檔案上傳並即時顯示進度條。核心原理為:前端發起上傳請求後,透過輪詢後端 API 取得進度百分比,動態更新進度條寬度與文字顯示。
<head>
<title>Index</title>
<style type="text/css">
#statusBorder { position:relative; height:5px; width:100px; border:solid 1px gray; display:none; }
#statusFill{ position:absolute; top:0; left:0; width:0px; background-color:Blue; height:5px; }
</style>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var uniqueId = " @Guid.NewGuid().ToString()";
$(document).ready(function (event) {
$('#startProcess').click(function () {
$.post("Home/StartLongRunningProcess",{ id: uniqueId }, function (data) {
if (data == "null") {
alert("檔案為空!");
} else {
$('#statusBorder').show();
getStatus();
}
}, "multipart/form-data");
event.preventDefault;
});
});
function getStatus() {
var url = 'Home/GetCurrentProgress/' + uniqueId;
$.get(url, function (data) {
if (data != "100") {
$('#status').html(data);
$('#statusFill').width(data);
window.setTimeout("getStatus()", 100);
} else {
$('#status').html("Done");
$('#statusBorder').hide();
alert("檔案儲存成功");
}
});
}
</script>
</head>
<body>
<div>
<div id="status"></div>
<h2>@Html.Encode(ViewData["Message"]) </h2>
<div>
<input id="File1" type="file" name="file" />
<input id="startProcess" type="submit" value="提交" />
</div>
<br />
<div id="statusBorder">
<div id="statusFill"></div>
</div>
</div>
</body>
</html>
Guid.NewGuid() 產生唯一識別碼,區分多使用者同時上傳$.post 發起上傳,$.get 輪詢進度 APIStartLongRunningProcess 與 GetCurrentProgress 兩個 Action此方案相容舊版瀏覽器,是 HTML5 File API 普及前的經典實作模式。