[eluser]cyberjunkie[/eluser]
Ok I finally got it to work, here is the full code. I'm also re-sizing the uploaded file. Note: I changed the name of my file input to
entry_image so I had to add that in the function argument
Code:
$this->upload->do_upload('entry_upload')
Code:
function create()
{
$this->form_validation->set_rules('content', 'Entry', 'trim|required|xss_clean');
$this->form_validation->set_rules('entry_upload', 'Image', 'callback__file_validation');
if ($this->form_validation->run() == FALSE)
{
//Load View
}
else
{
$entry_image = NULL; //leave NULL if no file uploaded
if ($_FILES['entry_upload']['error'] == 0) //There is no error, the file uploaded with success.
{
$entry_image = $this->upload->file_name; //set to file name
}
$data = array (
'user_id' => $this->tank_auth->get_user_id(),
'content' => $this->input->post('content'),
'entry_image' => $entry_image
);
$this->Entries_model->create_entry($data);
$this->session->set_flashdata('success', 'Entry added!');
//redirect
}
}
Callback. First I'm checking to see if a file was selected before validating. This is handy of you don;t want file uploads to be required.
Code:
function _file_validation()
{
if ($_FILES['entry_upload']['error'] !== 4) //if file selected
{
$user_id = $this->tank_auth->get_user_id();
$config['upload_path'] = "./uploads/entries/{$user_id}";
$config['allowed_types'] = 'jpg|png';
$config['encrypt_name'] = TRUE;
$config['overwrite'] = FALSE;
$config['max_size'] = '800'; //in KB
$this->load->library('upload', $config);
if (! $this->upload->do_upload('entry_upload'))
{
//set file errors
$this->form_validation->set_message('_file_validation', $this->upload->display_errors('', ''));
return FALSE;
}
else
{
//Resize Image
$config['image_library'] = 'gd2';
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 120;
$config['height'] = 120;
$this->load->library('image_lib', $config);
if (! $this->image_lib->resize())
{
//set file errors
$this->form_validation->set_message('_file_validation', $this->image_lib->display_errors('', ''));
return FALSE;
}
return TRUE;
}
}
return TRUE;
}