在CodeIgniter框架中处理文件上传时,最佳实践是将上传逻辑放在控制器中,而非模型。以下是详细分析:
$_FILES
)、调用业务逻辑。$_FILES
:上传类需处理原始文件流,控制器能直接获取上传的临时文件。$this->response()
或加载视图。// application/controllers/Upload.php
class Upload extends CI_Controller {
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->model('file_model');
$this->file_model->save_file_meta($data['upload_data']);
$this->load->view('upload_success', $data);
}
}
}
模型仅处理上传后的数据(如文件路径存储):
// application/models/File_model.php
class File_model extends CI_Model {
public function save_file_meta($file_data) {
$data = array(
'filename' => $file_data['file_name'],
'path' => $file_data['full_path'],
'uploaded_at' => date('Y-m-d H:i:s')
);
$this->db->insert('files', $data);
return $this->db->insert_id();
}
}
upload_path
是否可写(权限需设为755
或777
)。allowed_types
包含上传文件的扩展名。max_size
或提示用户压缩文件。$config['file_name']
避免文件名冲突或注入。循环处理$_FILES
数组:
foreach ($_FILES['userfiles']['name'] as $key => $name) {
$_FILES['userfile']['name'] = $name;
$_FILES['userfile']['tmp_name'] = $_FILES['userfiles']['tmp_name'][$key];
// ...其他字段赋值
$this->upload->do_upload('userfile');
}
没有搜到相关的文章