「要上傳幾張圖?」這種問題,最笨的解法是硬寫十個 file 欄位讓使用者自己忽略。聰明一點的做法是:讓使用者先說要幾張,再用 JavaScript 動態產生對應數量的欄位。以下是一個最小可運作的示範。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>上傳多圖片</title>
<script type="text/javascript">
function JM_wu(ob) { ob.style.display = "none"; }
function JM_you(ob) { ob.style.display = ""; }
function createForm(textN, number) {
data = "";
if (number < 11 && number > -1) {
for (i = 1; i <= number; i++) {
data = data + "<input name='" + textN + i + "' type='file'>"
+ "<input type='button' value='上傳" + i + "' onclick=javascript:uppic('more" + i + "','more" + i + "')><br>";
}
if (document.layers) {
document.layers.cust.document.write(data);
document.layers.cust.document.close();
} else if (document.all) {
cust.innerHTML = data;
}
} else {
window.alert("請不要超過 10 張圖片。");
}
}
</script>
</head>
<body>
<form name="prodtable" action="">
<input type="radio" name="more_pic" checked value="0" onclick="JM_wu(s1)">無
<input type="radio" name="more_pic" value="1" onclick="JM_you(s1)">有
<span id="s1" style="display:none">
數量:
<input name="more" type="text" value='1' size='5' maxlength='2'>
<input type="button" value="產生欄位" onclick="createForm('more', document.prodtable.more.value);">
<span id="cust" style="position: relative;"></span>
</span>
</form>
</body>
</html>
JM_wu 與 JM_you 負責切換「要不要多圖」的區塊;createForm 則依輸入的數字,用迴圈把 input 字串組出來,塞進 id="cust" 的容器。上限刻意寫成 10,避免使用者輸入 999 把頁面炸掉。
這份示範的骨架很值得學,但用 document.write 與 document.all 的寫法屬於上一個時代,有幾個地方值得換掉:
<input type="file" multiple>,一次就能選多張,不必動態產生多個欄位。FileList 讀取檔名、大小與 type,超過張數或體積上限就先攔下,能省掉一次無效的請求。upload.onprogress 就能畫出真實百分比,比「上傳中…」的轉圈圖有用。也就是說,這個小例子真正的價值在於示範「表單可以依需求動態長出來」這個思路;把它換成 file 輸入與 DOM API 之後,就是一段可以直接用在專案裡的程式了。