fileinfo 擴充writable/uploads/<?php namespace App\Controllers;
use CodeIgniter\Controller;
class Upload extends Controller
{
public function index()
{
return view('upload_form');
}
public function doUpload()
{
$files = $this->request->getFiles();
if (!isset($files['images'])) return redirect()->back()->with('error', '無檔案');
$results = ['success' => [], 'errors' => []];
$allowedTypes = ['image/jpeg','image/png','image/gif','image/webp'];
$maxSize = 5 * 1024 * 1024; // 5MB
$uploadDir = WRITEPATH . 'uploads/' . date('Y-m-d') . '/';
foreach ($files['images'] as $file) {
if ($file->getError() !== UPLOAD_ERR_OK) {
$results['errors'][] = $file->getClientName() . ': ' . $file->getErrorString();
continue;
}
if ($file->getSize() > $maxSize) {
$results['errors'][] = $file->getClientName() . ': 檔案過大';
continue;
}
if (!in_array($file->getMimeType(), $allowedTypes)) {
$results['errors'][] = $file->getClientName() . ': 型別不允許';
continue;
}
$newName = $file->getRandomName(); // 隨機檔名,含副檔名
if ($file->move($uploadDir, $newName)) {
$results['success'][] = [
'original' => $file->getClientName(),
'stored' => $newName,
'path' => 'uploads/' . date('Y-m-d') . '/' . $newName,
'size' => $file->getSize(),
];
} else {
$results['errors'][] = $file->getClientName() . ': 移動失敗';
}
}
return $this->response->setJSON($results);
}
}
<form method="post" action="= site_url('upload/doUpload') ?>" enctype="multipart/form-data">
= csrf_field() ?>
<input type="file" name="images[]" multiple accept="image/*" required>
<button type="submit">上傳</button>
</form>
<script>
document.querySelector('form').addEventListener('submit', async (e) => {
e.preventDefault();
const fd = new FormData(e.target);
const res = await fetch(e.target.action, {method: 'POST', body: fd, headers: {'X-Requested-With': 'XMLHttpRequest'}});
const data = await res.json();
data.success.forEach(f => console.log('OK:', f.path));
data.errors.forEach(err => console.error('ERR:', err));
});
</script>
public $upload = [
'images' => [
'label' => '上傳圖片',
'rules' => 'uploaded[images]|max_size[images,5120]|mime_in[images,image/jpeg,image/png,image/gif,image/webp]',
],
];
控制器可簡化為:if (!$this->validate('upload')) return $this->response->setJSON(['errors' => $this->validator->getErrors()]);
exec("clamscan {$file->getTempName()}") 非同步處理Image::withFile($path)->fit(800,600)->save($path) (CodeIgniter Image 擴充)$file->move($s3Path) 需配合 Flysystem 適配器attachments 表,關聯業務實體