最近在實做多重檔案上傳,寫過一篇 [PHP] pear 模組 HTTP_Upload 多重檔案上傳 Multiple files upload,那一開始我先設定只能上傳5個檔案,後來想想動態的話比較方便,畢竟現在網站都講求 web2.0,所以就利用 jQuery 來動態新增 input file 欄位,作法其實很簡單,不難的喔。其實還有 jQuery Confirm Plugin 可以利用它來確定使用者是否刪除檔案。
之前介紹的上傳檔案 html 部份:
<head>
</head>
<body>
<form name="fileuploadexample2" method="POST" enctype="multipart/form-data" action="">
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64">
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
改成:
<head>
</head>
<body>
<form name="fileuploadexample2" method="POST" enctype="multipart/form-data" action="">
<input type="button" id="add_button" name="add_button" value="增加附加檔案">
<div id="add_file_button"></div>
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />
<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64">
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
jQuery 的部份:
$("#add_button").click
(
function()
{
$("#add_file_button").append('<input type="file" name="f[]"> 檔案名稱:<input type="text" name="file_show_name[]" value="" size="32" maxlength="64"><br />');
}
);
$("a[id='del_file[]']").click(function(){
if (confirm('確定刪除檔案')) {
return true;
}
return false;
});
});
這樣大致少就可以了喔,可以動態新增檔案,那處理檔案上傳部份,可以利用 PHP 的 for 加上 count 函式,來處理動態表單。