CodeIgniter 的 Upload 類庫支援單檔上傳,批量上傳需自行遍歷 $_FILES 陣列。以下提供兩種常見寫法供參考。
<?php
public function multiple_uploads() {
// 載入上傳類庫
$this->load->library('upload');
// 統一配置
$config = array(
'upload_path' => './uploads/',
'allowed_types' => 'jpg|png|gif',
'max_size' => 500, // KB
'max_width' => 1024,
'max_height' => 768,
);
$this->upload->initialize($config);
// 遍歷所有上傳欄位
foreach ($_FILES as $key => $value) {
if (!empty($value['name'])) { // 修正:應檢查 $value['name']
if ($this->upload->do_upload($key)) {
// 成功:取得檔案資訊
$data = $this->upload->data();
// 寫入資料庫、返回 JSON 等後續邏輯
log_message('debug', "上傳成功: {$data['file_name']}");
} else {
// 失敗:記錄錯誤
log_message('error', $this->upload->display_errors());
}
}
}
}
?>
注意:原文 if (!empty($key['name'])) 應為 if (!empty($value['name'])),$key 是欄位名稱字串。
<?php
function upload() {
$config = array(
'upload_path' => './uploads/', // 相對於 index.php
'allowed_types' => 'gif|jpg|png|zip|gz', // 順序影響檢測,建議圖片優先
'max_size' => 1024,
'max_width' => 1024,
'max_height' => 768,
'file_name' => time(), // 使用時間戳避免中文檔名問題
);
$this->load->library('upload', $config);
// 處理多檔案:$_FILES['userfile'] 為陣列結構
$files = $_FILES['userfile'];
$count = count($files['name']);
for ($i = 0; $i < $count; $i++) {
// 重組單檔結構供 do_upload 使用
$_FILES['single'] = array(
'name' => $files['name'][$i],
'type' => $files['type'][$i],
'tmp_name' => $files['tmp_name'][$i],
'error' => $files['error'][$i],
'size' => $files['size'][$i],
);
if ($this->upload->do_upload('single')) {
$data = $this->upload->data();
echo "成功: {$data['file_name']}<br>";
} else {
echo "失敗: {$this->upload->display_errors()}<br>";
}
}
}
?>
upload_path 相對於 index.php,錯誤會報 The upload path does not appear to be validfile_name = time() 或 uniqid() 重命名zip|gz|png|gif|jpg 正確,png|gif|jpg|zip|gz 可能導致圖片被誤判為 application/octet-streamuploads/ 目錄可寫(chmod 777 或設定正確擁有者)上傳類庫已知儲存目錄,資料庫只需存檔名。若目錄按日期動態生成,組合相對路徑存入即可。也可在配置檔定義常量統一管理。