Codeigniter上传可选

时间:2012-01-16 12:12:02

标签: php codeigniter upload

我在Google中查找了这个,并在stackoverflow上找到了不同的答案。并且可能有一个很好的答案,但我仍然不知道如何在我自己的代码中实现它。

我有自己的公共功能来上传图片,但现在我希望它是可选的。此时有人需要上传文件以通过验证,我该如何选择?

我的职能:

public function _do_upload_image()
{
    $config['upload_path'] = './company_images/';
    $config['allowed_types'] = 'jpg|jpeg|png';

    $this->load->library('upload', $config);

    if (!$this->upload->do_upload())
    {
        $this->form_validation->set_message('_do_upload_image', $this->upload->display_errors());
    }
    else
    {
        $this->_upload_data = $this->upload->data();
    }

}

提前致谢

- 编辑 -

对于其他人,答案有效,当没有上传图片时,我给了我的file_name另一个名字。它看起来像这样:

public function _do_upload_image()
{
    $config['upload_path'] = './company_images/';
    $config['allowed_types'] = 'jpg|jpeg|png';
    $returnArr = array();

    $this->load->library('upload', $config);

    if (!$this->upload->do_upload())
    {
        $returnArr = array('file_name' => 'leeg.jpg');
    }
    else
    {
        $returnArr = $this->upload->data();
    }

    $this->_upload_data = $returnArr;
}

2 个答案:

答案 0 :(得分:1)

如果您的意思是需要将上传功能设为可选,那么您可以这样做:


public function _do_upload_image()
{
    $config['upload_path'] = './company_images/';
    $config['allowed_types'] = 'jpg|jpeg|png';
    $returnArr = array(); 

    $this->load->library('upload', $config);

    if ($this->upload->do_upload())
    {
        $returnArr  = $this->upload->data();
    }
    return $returnArr; //just return the array, empty if no upload, file data if uploaded
}

希望有意义

答案 1 :(得分:0)

  

codeigniter文件上传可选......工作完美..... :)。

----------控制器---------

function file()
{
 $this->load->view('includes/template', $data);
}

function valid_file()
{
 $this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');

 if ($this->form_validation->run()==FALSE) 
 {
    $this->file();
 }
 else
 {
  $config['upload_path']   = './documents/';
  $config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
  $config['max_size']      = '1000';
  $config['max_width']     = '1024';
  $config['max_height']    = '768';

  $this->load->library('upload', $config);

  if ( !$this->upload->do_upload('userfile',FALSE))
  {
    $this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());

    if($_FILES['userfile']['error'] != 4)
    {
        return false;
    }

  }
  else
  {
    return true;
  }
}

我只是使用这行,这使它可选,

if($_FILES['userfile']['error'] != 4)
{
 return false;
}

$_FILES['userfile']['error'] != 4 is for file required to upload.

你可以使用$_FILES['userfile']['error'] != 4使其成为不必要的,然后它将传递所需文件的错误 通过使用 return false ,可以很好地处理其他类型的错误, 希望它对你有用....