代码点火器,测试文件上传器是否有文件


Codeigniter, testing if file uploader has file

我的观点中有以下代码:

if (isset($stockists)) {
    $id = $stockists->ID;
    echo form_open_multipart($system_settings['admin_folder'].'/stockists/form/'.$id);
} 
else {
    echo form_open_multipart($system_settings['admin_folder'].'/stockists/form/');
}
 <?php echo "<input type='file' name='userfile' size='20' />"; ?>

其中还有许多其他文本输入字段,这些字段在提交时会发送到数据库。不过,文件加载器是我感兴趣的。

在我的控制器功能中,如何检查提交后上传器中是否存在文件?

以下重试为错误: $image = ($_FILES['userfile']);

如果上传器中存在文件,我需要检查条件语句。所以例如:

if ($_FILES['userfile']) {
  //do
}

但是这种方法不起作用。

超级全球 $_FILES

$_FILES['userfile']不是布尔值。

if (strlen($_FILES['userfile']['tmp_name']) > 0) {
    // Yes, is uploaded
}

在数组中,您还error

echo $_FILES['userfile']['error'];

代码点火器方法

CodeIgniter 有一个上传类可以为您完成这项工作。

CodeIgniter 的文件上传类允许上传文件。您可以设置各种首选项,限制文件的类型和大小。

下面是 CodeIgniter 文档中的示例:

<?php
class Upload extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }
    function index()
    {
        $this->load->view('upload_form', array('error' => ' ' ));
    }
    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())
        {
            $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);
        }
    }
}
?>

有关完整示例,请参阅文档:CI 文件上载类