php - 如何在codeigniter中上传多个文件字段
问题描述
我有 4 个文件字段的表单,我想正确上传这些文件。
我的代码如下:
public function do_upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$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);
}
}
解决方案
private function fileUpload($name, $config = []){
$config['upload_path'] = './uploads/';
$config['encrypt_name'] = TRUE;
$config['file_ext_tolower'] = TRUE;
$config['allowed_types'] = 'jpg|jpeg|png';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($name))
{
$error = array('error' => true, 'message' => $this->upload->display_errors());
return $error;
}
else
{
return array('error' => false, 'upload_data' => $this->upload->data());
}
}
在控制器中创建这个私有函数,当你必须上传带有文件字段名称的文件时调用这个函数,如果你想要一些其他配置,只需将配置数组作为下一个参数传递
$data = $this->fileUpload('site_logo_dark')
if($data['error']){
echo data['message']; // error message while uplaoding an file if have any
}else{
echo $data['upload_data']['file_name']; // return you a name of the file which you just upload it you can save it to the database
}
推荐阅读
- seo - 从网站/搜索引擎中完全删除 URL 的正确方法是什么?
- reactjs - 如何将初始值传递给带有选择字段的表单 - React Final Form?
- javascript - 递归迭代嵌套对象以更改所有出现的键值
- javascript - 如何在angularjs中明智地使用div的延迟加载
- operating-system - 找不到树命令
- javascript - JavaScript RegExp 密码验证不起作用
- python - 使用 max() 时获取“'builtin_function_or_method' 对象不可迭代”
- go - 是否有众所周知的四元数测试向量?惩罚幼稚实现的已知测试代码?
- ruby - 循序渐进的多条件循环中断
- google-apps-script - rangeElement.getStartOffset() 始终为 -1