有些表單需要讓使用者自行決定上傳檔案的數量,這時就得動態增刪 input[type=file] 欄位。以下示範以 jQuery 實作,並在刪除後重新編號,確保 name 保持連續。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>動態數量的檔案上傳</title>
<script type="text/javascript" src="jquery-2.2.0.min.js"></script>
<script type="text/javascript">
$(function () {
var i = 2;
$("#addFile").click(function () {
$(this).parent().parent().before(
"<tr class='file'><td>File" + i + ":</td>" +
"<td><input type='file' name='file" + i + "'/></td></tr>" +
"<tr class='desc'><td>Desc" + i + ":</td>" +
"<td><input type='text' name='desc" + i + "'/>" +
"<button id='delete" + i + "'>刪除</button></td></tr>"
);
i++;
// 為剛新增的刪除鈕掛上事件
$("#delete" + (i - 1)).click(function () {
var $tr = $(this).parent().parent();
$tr.prev("tr").remove(); // 一并移除對應的 file 列
$tr.remove();
// 刪除後重新編號,保持 name 連續
$(".file").each(function (index) {
var n = index + 1;
$(this).find("td:first").text("File" + n);
$(this).find("td:last input").attr("name", "file" + n);
});
$(".desc").each(function (index) {
var n = index + 1;
$(this).find("td:first").text("Desc" + n);
$(this).find("td:last input").attr("name", "desc" + n);
});
});
});
});
</script>
</head>
<body>
<table>
<tr class="file">
<td>File1:</td>
<td><input type="file" name="file1"/></td>
</tr>
<tr class="desc">
<td>Desc1:</td>
<td><input type="text" name="desc1"/></td>
</tr>
<tr>
<td><input type="submit" id="submit" value="上傳"/></td>
<td><button id="addFile">增加</button></td>
</tr>
</table>
</body>
</html>
・用 class 標記 file 與 desc 兩列成對出現,刪除時才能準確地兩列一起移除。若列數眾多,改成用 data-index 標記配對關係會更穩健。
・每次新增都要重新掛一次刪除事件,容易累積重複綁定。改用事件委派($(document).on('click', '.del-btn', handler))就能一次處理所有動態元素。
・傳送檔案時别忘了表單要加上 enctype="multipart/form-data",否則後端收不到檔案內容。
・若希望後端能直接以陣列方式接收,可以讓所有 file 欄位的 name 都寫成 file[],這樣就不需要重新編號了,程式碼會精簡不少。
最後一點是實務上的關鍵:前端動態增刪只是使用者體驗層面的事,伺服器端仍必須獨立驗證檔案的數量、大小與型別(不要只看副檔名,要檢查 MIME 或內容特徵),並為上傳的檔案重新命名,避免覆寫與路徑穿越風險。