2012-01-16 84 views
1

我在谷歌搜索这个和在stackoverflow上的不同答案。并且很可能他们有一个很好的答案,但是我仍然不知道如何在自己的代码中实现它。Codeigniter上传可选

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

我的功能:

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; 
} 

回答

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 
} 
 

希望是有道理的

+0

这样的作品,但有没有办法,如果没有图像上传我可以给['file_name']的价值:leeg.jpg? – Augus 2012-01-16 12:57:03

+0

Uhm nvm,我解决了所有我想要的功能。生病更新我的帖子! – Augus 2012-01-16 13:04:21

0

笨文件上传可选...作品完美..... :)

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

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; 
    } 
} 

我只是用$_FILES['userfile']['error'] != 4使用此线,使得它可选,

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

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

你u能使其unneccessory,那么它会通过此错误所需的文件和 与其他类型的伟大工程错误,如果有任何使用返回false, 希望它适用于你...