在 Web 開發中,文件上傳是常見功能。本文將詳細介紹如何使用 PHP 結合 JavaScript 實現動態多文件上傳,允許用戶通過點擊按鈕動態增加文件選擇框,一次提交上傳多個文件。
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>動態多文件上傳示例</title>
<script>
function addFileInput() {
const table = document.getElementById('fileTable');
const row = table.insertRow(-1);
const cell = row.insertCell(0);
cell.innerHTML = "<input type='file' name='filelist[]' size='50' />";
}
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<table id="fileTable" width="500" border="0">
<tr>
<td>
文件上傳列表
<input type="button" value="添加文件" onclick="addFileInput()" />
</td>
</tr>
<tr>
<td><input type="file" name="filelist[]" size="50" /></td>
</tr>
</table>
<br>
<input type="submit" name="submitfile" value="提交上傳" />
</form>
</body>
</html>
<?php
if (isset($_POST['submitfile'])) {
// 以年月建立子目錄,避免單目錄文件過多
$uploadDir = __DIR__ . '/uploads/' . date('Ym') . '/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$files = $_FILES['filelist'];
$count = count($files['name']);
$success = 0;
$failed = [];
for ($i = 0; $i < $count; $i++) {
// 跳過未選擇文件的輸入框
if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) continue;
// 錯誤檢查
if ($files['error'][$i] !== UPLOAD_ERR_OK) {
$failed[] = $files['name'][$i] . ' (錯誤代碼: ' . $files['error'][$i] . ')';
continue;
}
// 安全檢查:文件大小、類型等(此處略,實際項目務必加強)
$tmpName = $files['tmp_name'][$i];
$origName = basename($files['name'][$i]);
// 防止文件名衝突:加上時間戳前綴
$newName = date('YmdHis') . '_' . $origName;
$destPath = $uploadDir . $newName;
if (move_uploaded_file($tmpName, $destPath)) {
$success++;
echo "<div>✅ 文件上傳成功:{$origName} (類型: {$files['type'][$i]})</div>";
} else {
$failed[] = $origName . ' (移動失敗)';
}
}
echo "<hr><p>共成功上傳 {$success} 個文件。</p>";
if ($failed) {
echo "<p style='color:red'>失敗文件:<br>" . implode('<br>', $failed) . "</p>";
}
echo "<a href='upload.html'>返回繼續上傳</a>";
}
?>
掌握動態多文件上傳後,您可以輕鬆構建圖庫、附件系統、批量導入等實用功能。祝編碼愉快!