如何在codeigniter中上传不同的文件(图像和文档)

时间:2013-09-03 06:19:46

标签: codeigniter codeigniter-2

您好我是codeigniter的新手,请您帮我在代码点火器中插入多个文件(文档和图像)。这是我的示例代码

视图:

<label>Picture</label>
            <input type="file" name="userfile" size="100" /> 

<label>Document</label>
           <input type="file" name="documentfile" size="10" />

控制器:

 $m = $_FILES['userfile']['name'];
 $n = $_FILES['documentfile']['name'];
  if ($m !== "")
        {
            $config['upload_path'] = './upload_images/';
            $config['allowed_types'] = 'jpg|png|jpeg|gif';
            $config['max_size'] = '0'; // 0 = no file size limit
            $config['max_width']  = '0';
            $config['max_height']  = '0';
            $config['overwrite'] = TRUE;
            $this->load->library('upload', $config);
             $this->upload->do_upload();
             $upload_result = $this->upload->data();
        }
       elseif ($n !== "")
        {
            $config_document['upload_path'] = './upload_documents/';
            $config_document['allowed_types'] = 'pdf';
            $config_document['max_size'] = '0';
            $config_document['overwrite'] = TRUE;
            $this->load->library('upload', $config_document);
             $this->upload->do_upload();
             $upload_result2 = $this->upload->data();
        }   
 $image_filename = $upload_result['file_name'];
 $docu_filename = $upload_result2['file_name '];
$this->MODEL->add_asset($image_filename, $docu_filename);

我试图回显两个文件名并且它有效但我的$ docu_filename生成NULL值; 请帮忙。谢谢

1 个答案:

答案 0 :(得分:2)

简单只需检查上传文件的文件扩展名并根据该设置进行设置。还有一件事你必须设置你的html表单enctype。检查以下示例

表格查看

<form method="post" action="controller" enctype="multipart/form-data"> 
    <input type="file" name="test">
    <input type="submit" value="submit" />
</form>
控制器中的

 $path = $_FILES['test']['name'];
 $ext = pathinfo($path, PATHINFO_EXTENSION);
 $img_ext_chk = array('jpg','png','gif','jpeg');
 $doc_ext_chk = array('pdf','doc');

if (in_array($ext,$img_ext_chk))
        {
            $config['upload_path'] = './upload_images/';
            $config['allowed_types'] = 'jpg|png|jpeg|gif';
            $config['max_size'] = '0'; // 0 = no file size limit
            $config['max_width']  = '0';
            $config['max_height']  = '0';
            $config['overwrite'] = TRUE;
            $this->load->library('upload', $config);
             $this->upload->do_upload();
             $upload_result = $this->upload->data();
        }
       elseif (in_array($ext,$doc_ext_chk))
        {
            $config_document['upload_path'] = './upload_documents/';
            $config_document['allowed_types'] = 'pdf';
            $config_document['max_size'] = '0';
            $config_document['overwrite'] = TRUE;
            $this->load->library('upload', $config_document);
             $this->upload->do_upload();
             $upload_result2 = $this->upload->data();
        }