最近做專案遇到上傳相關的功能模組,上網找了不少資料。有一個依賴 jQuery 的 jquery.uploadify 類庫,功能相當完整,遺憾的是它靠 Flash 處理上傳,畫面上呈現不出傳統的 <input type="file" /> 選擇檔案介面。由於需求明確要求必須是傳統形態,只好捨棄這個方便的工具,自己研究一番,最後做出一個可用的靜態上傳功能。
後端用 ASP.NET,前端用 jQuery。
因為這個做法不會讓當前頁面刷新,但實際上完全沒用到任何 Ajax 技術——它靠的是 <form> 搭配 <iframe> 的組合。對 HTML 熟悉的朋友大概已經猜到了。
<form id="formFile" name="formFile" method="post"
action="/uploads.aspx" target="frameFile" enctype="multipart/form-data">
<input type="file" id="fileUp" name="fileUp" />
<div id="uploadLog"></div>
<br />
<img width="200" height="200" id="imgShow" alt="縮圖" />
</form>
<!--
關鍵在 target 屬性:它的值 frameFile 就是後面 iframe 的 name。
表單提交時,處理結果會被導向 iframe 內部載入,
因此當前頁面不會跳轉。
-->
<iframe id="frameFile" name="frameFile" style="display:none;"></iframe>
$(function () {
// 一選好檔案就自動送出,省去多按一次上傳按鈕
$('#fileUp').change(function () {
$('#uploadLog').html('開始上傳中....');
$('#formFile').submit();
});
});
// 由 iframe 內的後端頁面呼叫,用來回報結果
function uploadSuccess(msg) {
var parts = msg.split('|');
if (parts.length > 1) {
$('#imgShow').attr('src', parts[1]);
$('#uploadLog').html(parts[0]);
} else {
$('#uploadLog').html(msg);
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
HttpPostedFile file = Request.Files["fileUp"];
if (file == null)
{
Response.Write("<script>window.parent.uploadSuccess('請選擇檔案');</script>");
Response.End();
return;
}
string path = Server.MapPath("~/Test/");
string ext = Path.GetExtension(file.FileName).ToLower();
// 副檔名檢查
if (ext != ".gif" && ext != ".jpg" && ext != ".jpeg" && ext != ".png" && ext != ".bmp")
{
Response.Write("<script>window.parent.uploadSuccess('檔案格式不正確,僅支援 .gif、.jpg、.png、.bmp');</script>");
Response.End();
return;
}
// 檔案大小檢查
if (file.ContentLength > 1048576)
{
Response.Write("<script>window.parent.uploadSuccess('檔案不可超過 1 MB');</script>");
Response.End();
return;
}
// 存檔
string imageUrl = path + file.FileName;
file.SaveAs(imageUrl);
// 成功時回傳「訊息|路徑」兩個部分,以 | 分隔
Response.Write("<script>window.parent.uploadSuccess('上傳成功|/Test/"
+ file.FileName + "');</script>");
Response.End();
}
catch
{
Response.Write("<script>window.parent.uploadSuccess('上傳失敗');</script>");
Response.End();
}
}
iframe 拿到表單資料後,會在自身內部載入 action 指定的頁面並刷新——但因為它被 display:none 藏起來了,使用者看起來就像是無刷新上傳。後端則透過 window.parent.uploadSuccess() 把結果丟回外層頁面。
這個技巧的優點是簡單、相容性極好、不需要任何外掛。但仍有幾點值得留意:
Content-Type 並讀取檔案標頭(magic number)確認真實型別。file.FileName 存檔有風險,可能包含路徑跳脫字元。建議用 GUID 重新命名,只保留副檔名。Response.Write 輸出 script 標籤,若檔名或訊息中含引號,會破壞 script。改名為 GUID 後這個問題自然消失。如果日後可以放寬「必須是傳統檔案選擇介面」的限制,改用 FormData 搭配 $.ajax() 才是真正的 Ajax 上傳,還能加上進度條。