CodeIgniter 內建的 檔案上傳類庫 提供完整的上傳處理流程,支援檔案類型限制、尺寸檢查、重新命名、縮圖等功能。本文以圖片上傳為例,詳述表單建立、控制器處理與關鍵方法。
enctype="multipart/form-data");<form method="post" action="<?=base_url()?>admin/img_upload/" enctype="multipart/form-data">
<div style="margin:0 0 0.5em 0em;">
<input type="file" name="userfile" size="20" class="button" />
<input type="submit" value=" 上傳 " class="button" />
</div>
</form>
關鍵點:name="userfile" 為預設檔案欄位名稱,若不同需在 do_upload('custom_name') 指定。
public function img_upload() {
$this->load->helper('url');
$config['upload_path'] = './images/' . date('Ym', time()) . '/'; // 按年月分目錄
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = date('Y_m_d', time()) . '_' . sprintf('%02d', rand(0, 99)); // 自訂檔名
$config['max_size'] = '500'; // KB
$config['max_width'] = '1024'; // px
$config['max_height'] = '768'; // px
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
// 載入錯誤視圖或回傳 JSON
} else {
$data = array('upload_data' => $this->upload->data());
// 處理成功邏輯:記錄資料庫、回傳檔案資訊等
}
}
| 配置項 | 說明 | 預設值 |
|---|---|---|
| upload_path | 儲存路徑,需可寫入 | 無 |
| allowed_types | 允許副檔名,用 | 分隔 | 無 |
| file_name | 指定檔名(不含副檔名) | 原檔名 |
| overwrite | 同名檔案是否覆蓋 | FALSE |
| max_size | 最大檔案大小(KB),0 為不限制 | 0 |
| max_width / max_height | 圖片最大寬高(px) | 0 |
| encrypt_name | 是否加密檔名 | FALSE |
| remove_spaces | 檔名空格轉底線 | TRUE |
$this->upload->do_upload([$field_name]):執行上傳,成功回傳 TRUE,失敗回傳 FALSE;$this->upload->display_errors([$open, $close]):取得錯誤訊息字串,不自動輸出,可自訂包裹標籤;$this->upload->data():回傳上傳成功檔案的詳細資訊陣列(含 file_name、full_path、file_size、image_width 等)。upload_path 是否存在,不存在則 mkdir($path, 0755, true);$_FILES['userfile']['name'] 為陣列時,需迴圈處理;image_lib 進行縮圖、水印、裁切等操作。善用上傳類庫的豐富配置,能快速建立安全、穩健的檔案上傳功能。