LigerUI 的 Grid 與 Form 有各自的欄位定義方式,要讓「上傳檔案後把路徑寫回表格」這件事順暢運作,需要四個部分配合:載入外掛、隱藏的上傳容器、Grid/Form 欄位設定,以及伺服器端接收的 aspx 頁面。
<script src="../lib/js/ajaxfileupload.js" type="text/javascript"></script>
<script src="../lib/js/ligerui.expand.js" type="text/javascript"></script>
ajaxfileupload.js 提供不換頁上傳的能力,ligerui.expand.js 則是擴充後的 LigerUI 元件。
<div id="AppendBill_Div" style="display:none;">
<%-- 上傳 - 單 --%>
<table style="height:100%;width:100%">
<tr style="height:40px">
<td style="width:20%">圖標:</td>
<td><input type="file" style="width:200px" id="fileupload" name="fileupload" /></td>
</tr>
</table>
</div>
這個 div 預設隱藏,之後會作為 LigerUI 對話框的內容被彈出來。
Grid 中需要一欄來顯示已上傳的路徑:
{ display: "掃描件", name: "AppendBillPath", width: 120, type: "text", align: "left" }
Form 則需要「隱藏欄位 + 可點擊選擇的下拉」兩項搭配,並註冊開啟前的事件:
{ name: "AppendBillPath1", type: "hidden" }, // 上傳-【5】
{ display: "掃描件", name: "AppendBillPath", comboboxName: "AppendBillPath2",
newline: true, labelWidth: 100, width: 150, space: 30, type: "select", options: {} } // 上傳-【6】
$.ligerui.get("AppendBillPath2").set('onBeforeOpen', f_selectAppendBillPath_1) // 上傳-【7】
技巧在於把下拉選單當成「檔案選擇器」的觸發器:使用者點它時,攔截 onBeforeOpen 事件,改為彈出自己的上傳對話框,這樣就不會真的展開下拉清單。
// #region ===== 【上傳掃描件視窗】
var AppendBillPathDetail = null;
function f_selectAppendBillPath_1() {
var imageurl = $("#AppendBill").val(); // 單號
if (imageurl.length == 0) {
LG.showError("您沒有輸入單號,請輸入隨單號!");
return;
}
if (AppendBillPathDetail) {
AppendBillPathDetail.show(); // 已建立過就直接顯示
} else {
AppendBillPathDetail = $.ligerDialog.open({
target: $("#AppendBill_Div"),
title: '添加圖標',
width: 360, height: 170, top: 170, left: 280,
buttons: [
{ text: '上傳', onclick: function () { AppendBillPath_save(); } },
{ text: '取消', onclick: function () { AppendBillPathDetail.hide(); } }
]
});
}
}
function AppendBillPath_save() {
var imgurl = $("#fileupload").val();
var extend = imgurl.substring(imgurl.lastIndexOf("."), imgurl.length).toLowerCase();
if (extend == ".jpg" || extend == ".jpeg" || extend == ".png"
|| extend == ".gif" || extend == ".bmp") {
// 副檔名合法,繼續
} else {
LG.showError("請上傳 jpg, jpeg, png, gif, bmp 格式的圖片檔");
return;
}
var imageurl = $("#AppendBill").val();
$.ajaxFileUpload({
url: "../handle/ImageUpload.aspx?imageurl=" + imageurl, // 上傳-【9】
secureuri: false,
fileElementId: "fileupload",
dataType: "text",
success: function (data, status) {
LG.tip(data);
f_reload(); // 重載 Grid 讓新路徑出現
},
error: function (data, status, e) {
LG.showError(data);
}
});
}
// #endregion
幾個設計意圖值得留意。AppendBillPathDetail 這個變數用來快取對話框物件,第二次點擊時直接 show(),不必重新建立,省下資源也避免重複註冊事件。f_reload() 是關鍵的一步——上傳成功後若不重載 Grid,畫面上不會看到新的路徑。
string url = Server.MapPath("/Image/" + gfilename + filenameext); // 執行上傳操作
存檔完成後把可讀的相對路徑回傳給前端,前端的 success 回呼就能用 LG.tip(data) 顯示提示。
範例只在前端檢查副檔名,這是不足的——副檔名可以由使用者偽造,攻擊者把 shell.aspx 改名成 shell.jpg 就能繞過。伺服器端至少要做到:
HttpPostedFile.ContentType 與檔案簽章(magic number)雙重驗證,而非只看副檔名。把這些補上,這個上傳模組才能放心用在真實環境。