在 AJAX 普及前,檔案上傳無法透過 XMLHttpRequest 直接送出。傳統做法利用隱藏 <iframe> 作為 <form target>,搭配伺服器端 IHttpHandler 接收檔案流,並透過另一支 IHttpAsyncHandler 讀取暫存進度回傳 JSON,前端以 jQuery UI Progressbar 顯示。本文完整呈現此經典架構。
<!DOCTYPE html>
<html>
<head>
<link href="Styles/jquery-ui-1.12.1.custom.css" rel="stylesheet" />
<script src="Scripts/jquery-3.6.0.min.js"></script>
<script src="Scripts/jquery-ui-1.12.1.custom.min.js"></script>
</head>
<body>
<form id="uploadForm" target="uploadFrame" enctype="multipart/form-data" action="UploadHandler.ashx" method="POST">
<div id="progressBar" style="width:300px;"></div>
<span id="progressText">0%</span>
<br /><br />
<input type="file" id="fileUpload" name="fileUpload" />
<input type="submit" value="上傳" id="btnSubmit" />
<iframe id="uploadFrame" name="uploadFrame" style="display:none;"></iframe>
</form>
<script>
$(function () {
$("#btnSubmit, #fileUpload").button();
$("#progressBar").progressbar({ value: 0 });
$("#uploadForm").submit(function () {
if (!$("#fileUpload").val()) { alert("請選擇檔案"); return false; }
$("#progressBar").progressbar("value", 0);
$("#progressText").text("0%");
startProgressPolling();
});
});
function startProgressPolling() {
var timer = setInterval(function () {
$.getJSON("ProgressHandler.ashx", function (data) {
if (data.loaded !== undefined) {
$("#progressBar").progressbar("value", data.loaded);
$("#progressText").text(data.loaded + "%");
if (data.loaded >= 100) clearInterval(timer);
}
});
}, 500);
}
</script>
</body>
</html>
public class UploadHandler : IHttpHandler
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count == 0 || string.IsNullOrEmpty(context.Request.Files[0].FileName))
{
context.Response.StatusCode = 400;
context.Response.Write("無檔案");
return;
}
var file = context.Request.Files[0];
var savePath = Path.Combine(context.Server.MapPath("~/Uploads"), Path.GetFileName(file.FileName));
// 確保目錄存在
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
// 儲存檔案 (大檔建議分塊寫入)
file.SaveAs(savePath);
// 回傳結果給 iframe
context.Response.ContentType = "text/html";
context.Response.Write("<script>parent.uploadComplete('" + file.FileName + "');</script>");
}
}
需搭配暫存機制 (如 Application、Cache、資料庫或共享記憶體) 記錄已上傳位元組數。簡易示範:
public class ProgressHandler : IHttpHandler
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext context)
{
// 實務上應從共享儲存讀取目前上傳進度
// 此處僅模擬
var progress = (int?)context.Application["UploadProgress"] ?? 0;
context.Response.ContentType = "application/json";
context.Response.Write($"{{\"loaded\": {progress}}}");
}
}
關鍵點:UploadHandler 需在接收串流時定期更新進度值至共享儲存。大型檔案建議手寫 IHttpAsyncHandler 非同步讀取 InputStream,每讀取一塊更新進度。
xhr.upload.onprogress,無需 iframe、無需輪詢,IE10+ 全支援。IFormFile、MultipartBodyLengthLimit,搭配前端元件極簡單。理解 iframe + Handler 架構有助於維護舊專案,但新專案請直接採用 HTML5 原生上傳與現代前端元件,開發效率與使用者體驗大幅提升。