codeigniter upload file error

2019-03-06 11:08发布

问题:

I am receiving the error "You did not select a file to upload." When I am attempting to upload a photo using this code:

function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('session');
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'title', 'trim|required|max_length[255]');
$this->form_validation->set_rules('description', 'description', 'trim|required|max_length[2550]');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');

$data['title'] = $this->input->post('username');
$data['description'] = $this->input->post('description');
if($this->form_validation->run() == FALSE)
{
  $this->load->view('upload_form', $data);
}
else
{
  $this->load->helper('string');
  $config['upload_path'] = realpath($_SERVER['DOCUMENT_ROOT'] . '/uploads') . '/';
  $config['allowed_types'] = 'gif|jpg|png';
  $config['max_size'] = '5000';
  $config['max_width'] = '10240';
  $config['max_height'] = '10240';
  $config['overwrite'] = FALSE;
  $config['file_name'] =  random_string('alpha', 6);
  $config['remove_spaces'] = TRUE;

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

  if(!$this->upload->do_upload('file'))
  {
    $error = array('upload_message' => $this->upload->display_errors());
    $this->load->view('upload_form', $error);
  }
  else
  {
    //do upload stuff
  }
}

And this is the view:

<?php echo form_open('upload'); ?>
<h5>Title: </h5>
<br />
<?php echo form_input('title', set_value('title')); ?>
<?php $a = form_error('title'); ?>
<br />
<?php echo '<h5>'; echo $a=="" ? '<br />' : $a.'<br />'; echo '</h5>'; ?>
<h5>Description: </h5>
<br />
<?php echo form_textarea('description', set_value('description')); ?>
<?php $a = form_error('description'); ?>
<br />
<?php echo '<h5>'; echo $a=="" ? '<br />' : $a.'<br />'; echo '</h5>'; ?>
<h5>Upload: </h5>
<br />
<?php echo form_upload('file'); ?>
<?php $a = (isset($upload_message) ? $upload_message : "<br/>&nbsp<br /><br />"); ?>
<?php echo '<h5>'; echo $a=="" ? '<br />a' : $a.''; echo '</h5>'; ?>
<br />
<?php echo form_submit('upload', 'Upload'); ?>
<?php form_close(); ?>

I have made a test upload form with the same config and it works perfectly. When I try and use this form however, I am receiving the error "You did not select a file to upload."

回答1:

You need to use form_open_multipart() instead of form_open(). Your test script couldn't have possibly worked without this.



回答2:

use form_open_multipart() method instead form_opne(). its worked for me