做專案時遇到一個問題:若用傳統的 FileUpload 控制項上傳檔案,頁面必然刷新,而頁面上用 JS 動態拼出的元素會全部消失。既要上傳又不能刷新,ajaxfileupload 這個 jQuery 外掛是個可行選擇。
它是 jQuery 的外掛,使用前必須先引入 jQuery。
值得先理解它怎麼做到的:真正的 XMLHttpRequest 在舊標準下無法上傳檔案。這個外掛的做法是動態建立一個隱藏的 <iframe> 作為表單的提交目標,繞過整頁導航,再從 iframe 中讀回伺服器的回應。
理解這一點很重要,因為它解釋了後面幾個看似奇怪的設定——例如後端 ContentType 為何必須寫 text/html 而非 json。
$.ajaxFileUpload({
url: '/Web/Teacher/ImportAchievements.ashx',
secureuri: false,
fileElementId: 'fulAchievements',
dataType: 'json',
success: function (data, status) {
alert(data[0]);
}
});
url:接收檔案的後端程式路徑。secureuri:是否對上傳採加密連線(HTTPS)。fileElementId:<input type="file"> 的 id。這裡有個容易踩的坑——後端是以 name-value 形式收資料的,但外掛在建立 iframe 表單時是依 name 傳遞,所以那個 file input 必須同時具備 name 屬性,否則後端收到 null。dataType:回應的資料類型,一般填 json。success:上傳成功後的回呼函數。
public void ProcessRequest (HttpContext context) {
// 關鍵:雖然前端宣告 dataType 是 json,這裡一定要寫 text/html
context.Response.ContentType = "text/html";
// 取得前端傳來的所有檔案
HttpFileCollection files = HttpContext.Current.Request.Files;
// 存檔到網站目錄
files[0].SaveAs(context.Server.MapPath("/Web/uploadFiles/Achievements.xls"));
// 回傳 JSON 格式的提示字串
string result = "[" + "\"" + "成績導入成功" + "\"" + "]";
context.Response.Write(result);
}
因為 iframe 模式下的回應是被當成一份 HTML 文件載入的。若宣告為 application/json,瀏覽器可能觸發下載行為或是以純文字顯示,外掛就讀不到內容。內容本身是 JSON 字串,但 Content-Type 標頭要寫 text/html——這個矛盾正是 iframe 上傳法的歷史包袱。
必須誠實說明:ajaxfileupload 的最後更新停在 2011 年前後,其 iframe 技巧在現代環境下有幾個實際問題:
progress 事件,大檔案上傳時使用者只能看著畫面等待。HTML5 的 FormData 讓 XMLHttpRequest 與 fetch 都能原生上傳檔案,程式碼更短而且功能更完整。
<input type="file" id="fileInput" name="file" accept=".xls,.xlsx">
<button type="button" id="uploadBtn">上傳</button>
<progress id="bar" value="0" max="100"></progress>
<script>
document.getElementById("uploadBtn").addEventListener("click", function () {
var input = document.getElementById("fileInput");
if (!input.files.length) { alert("請選擇檔案"); return; }
var fd = new FormData();
fd.append("file", input.files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Web/Teacher/ImportAchievements.ashx");
// 真實的上傳進度
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
document.getElementById("bar").value = (e.loaded / e.total) * 100;
}
};
xhr.onload = function () {
if (xhr.status === 200) {
try {
var data = JSON.parse(xhr.responseText);
alert(data[0]);
} catch (err) {
console.error("回應格式不正確", xhr.responseText);
}
} else {
alert("上傳失敗:HTTP " + xhr.status);
}
};
xhr.onerror = function () { alert("網路錯誤"); };
xhr.send(fd); // 注意:不要手動設定 Content-Type,瀏覽器會自動加上 boundary
});
</script>
若不需要進度條,用 fetch 更簡潔:
fetch("/api/upload", { method: "POST", body: fd })
.then(function (r) {
if (!r.ok) throw new Error("HTTP " + r.status);
return r.json();
})
.then(function (data) { console.log(data); });
原範例的 ASP.NET 端有幾個需要補強的地方:
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "application/json"; // 現代做法可以直接用 json
if (context.Request.Files.Count == 0) {
context.Response.StatusCode = 400;
context.Response.Write("{\"error\":\"未收到檔案\"}");
return;
}
var file = context.Request.Files[0];
// 只允許預期的副檔名,避免任意檔案寫入
var allowed = new[] { ".xls", ".xlsx" };
var ext = System.IO.Path.GetExtension(file.FileName).ToLowerInvariant();
if (!allowed.Contains(ext)) {
context.Response.StatusCode = 400;
context.Response.Write("{\"error\":\"不支援的檔案格式\"}");
return;
}
// 檔名不要直接用使用者提供的值,改為 GUID 避免路徑穿越與覆寫
var safeName = System.Guid.NewGuid().ToString("N") + ext;
var path = context.Server.MapPath("~/Web/uploadFiles/" + safeName);
file.SaveAs(path);
context.Response.Write("[\"成績導入成功\"]");
}
安全性重點:直接 SaveAs 使用者提供的檔名,是知名的路徑穿越(Path Traversal)漏洞來源。../../web.config 這種檔名可以覆寫掉網站設定。務必自行產生檔名,並驗證副檔名與檔案大小。