如何在不需要的情况下上传文件

时间:2013-08-20 00:41:10

标签: codeigniter file-upload

我正在做的是一个表单,你可以上传的文件的一部分是一个文件:

<input type="file" name="userfile" size="20" />

它工作正常但唯一的问题是如果用户没有选择文件程序崩溃。我尝试通过在控制器中添加if指令使其不需要:

if ($this->input->post('userfile')) {
            $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);
            $imagen = $this->upload->do_upload();
        }

但这种糟糕的尝试似乎不起作用,因为$this->input->post('userfile')不包含任何内容,无论用户是否选择了文件。

所以问题是:我怎么知道用户是否选择了一个文件,以便我可以在我的控制器上正确处理它?<​​/ p>

2 个答案:

答案 0 :(得分:1)

if($_FILES['userfile']['error'] == UPLOAD_ERR_OK)
{
   // A file was selected and uploaded to the server for further processing
}

Other possible values for the error field if you need to give more extensive feedback

答案 1 :(得分:1)

在PHP中,带有<input>的{​​{1}}元素会自动填充PHP数组$ _FILES而不是$ _POST,而codeigniter的type="file"函数会查找。

http://php.net/manual/en/reserved.variables.files.php

因此,您可以通过执行以下操作来检查用户是否上传了任何文件:

$this->input->post()