Codeigniter: Image Upload

2019-02-11 02:15发布

问题:

I have a large form, and I just added an file input to allow users to upload an image.

Here's the new HTML:

<input type="file" name="file_1" />
<input type="text" name="image_description_1" class="text-input"/>

Here's the new _submit function:

if($this->CI->input->post('file_1')){
    $config['overwrite'] = TRUE;
    $config['allowed_types'] = 'jpg|jpeg|gif|png';
    $config['max_size'] = 2000;
    $config['upload_path'] = realpath(APPPATH . '../assets/uploads/avatars');

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

    $image_data = $this->CI->upload->data();

    $image['description'] = $this->CI->input->post('image_description_1');
    $image['user_id'] = $id;
    $image['image'] = $image_data['file_name'];

    $this->CI->db->insert('report_images',$image);

}

The description and user_id are correctly getting submitted, but the file is lost.

Should I be doing something different? Not really sure what's going wrong.

回答1:

First of all don't get the do_upload() for granted, you have to validate the upload:

if ( ! $this->upload->do_upload('file_1'))
{
    // something went wrong, display errors
}   
else
{
    // everything is fine
}

Also, most likely it's your upload_path, check the document I linked to:

//You'll need a destination folder for your uploaded images. Create a folder at the root of your CodeIgniter installation called uploads and set its file permissions to 777.  
$config['upload_path'] = './uploads/';

So you may need to change your setting to something like:

$config['upload_path'] = './assets/uploads/avatars/';


回答2:

codeigniter expects your file input to be named userfile, unless you specify in your code like this,

$field_name = "some_field_name";
$this->upload->do_upload($field_name)


回答3:

I am not sure what the problem is. But May be the below links could help you.

Upload file bug in codeigniter

Also you can initialize the config to set preferences.

$this->upload->initialize($config);

File Uploading class in codeigniter



回答4:

Make sure the name of the input file is set to "userfile" because the upload function expects the files coming from an input field whose name is set to "userfile"