首页 > 解决方案 > 如何在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);
    }
}

在此处输入图像描述

标签: phphtmlcodeigniter

解决方案


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 
}

推荐阅读