簡體   English   中英

Codeigniter上傳可選

[英]Codeigniter upload optional

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

如果您的意思是需要將上傳功能設為可選,則可以執行以下操作:


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
}

希望有道理

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可以與其他類型的錯誤(如果有)一起使用,希望為你工作....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM