CodeIgniter 是一个轻量级的 PHP 框架,提供了文件上传类(Upload Class)来简化文件上传操作。当遇到图片无法上传的问题时,通常涉及以下几个方面的检查。
确保表单有以下属性:
<form method="post" action="upload/do_upload" enctype="multipart/form-data">
<input type="file" name="userfile">
<input type="submit" value="Upload">
</form>
enctype="multipart/form-data"
是必须的method="post"
是必须的name="userfile"
应与控制器中的名称一致正确的控制器代码示例:
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048; // 2MB
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
常见错误:
upload_path
路径不存在或不可写allowed_types
未包含要上传的文件类型max_size
设置过小上传目录必须存在且有写入权限:
mkdir uploads
chmod 755 uploads # 或 777 如果权限问题依然存在
检查 php.ini 中的以下设置:
upload_max_filesize = 2M
post_max_size = 8M
file_uploads = On
CodeIgniter 通过文件扩展名而非内容检测文件类型。如果需要更严格的检测,可以:
$config['file_ext_tolower'] = TRUE; // 强制小写扩展名
$config['detect_mime'] = TRUE; // 启用MIME类型检测
获取详细错误信息:
if (!$this->upload->do_upload('userfile')) {
$error = $this->upload->display_errors();
// 记录或显示错误
log_message('error', 'Upload error: '.$error);
show_error($error);
}
控制器 (Upload.php):
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
}
public function index() {
$this->load->view('upload_form');
}
public function do_upload() {
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|jpeg|png',
'max_size' => 2048,
'encrypt_name' => TRUE,
'remove_spaces' => TRUE
];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$data['error'] = $this->upload->display_errors();
$this->load->view('upload_form', $data);
} else {
$data['upload_data'] = $this->upload->data();
$this->load->view('upload_success', $data);
}
}
}
视图 (upload_form.php):
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<?php if (isset($error)) echo "<div style='color:red'>$error</div>"; ?>
<?= form_open_multipart('upload/do_upload'); ?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
// 在控制器中
foreach ($_FILES as $key => $value) {
if (!empty($value['name'])) {
if (!$this->upload->do_upload($key)) {
// 处理错误
} else {
// 处理上传成功
}
}
}
上传后自动处理图片:
$config['image_library'] = 'gd2';
$config['source_image'] = $upload_data['full_path'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 150;
$config['height'] = 100;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
通过以上方法和检查步骤,应该能够解决大多数 CodeIgniter 图片上传问题。
没有搜到相关的文章