Use CodeIgniter's class library for picture upload

  • 2021-06-28 12:11:28
  • OfStack

CodeIgniter's file upload class allows files to be uploaded.You can set up files of a specified type to be uploaded and of a specified size.

A common process for uploading files:

A form for uploading files that allows the user to select a file and upload it.
When the form is submitted, the file is uploaded to the specified directory.
At the same time, the file will be validated to meet the requirements you set.
1Once the file is uploaded successfully, a confirmation window for successful upload is returned.

Here is the form:

<form method="post" action="<?=base_url()?>admin/img_upload/" enctype="multipart/form-data" />
 <div style="margin:0 0 0.5em 0em;">
  <input type="file" name="userfile" size="20" class="button" />
  <input type="submit" value="  upload  " class="button" />
 </div>
</form>

Then here is the upload class:

public function img_upload()
{
 $this->load->helper('url');

 $config['upload_path'] = './images/'.date('Ym', time()).'/';
 $config['allowed_types'] = 'gif|jpg|png';
 $config['file_name'] = date('Y_m_d', time()).'_'.sprintf('%02d', rand(0,99));
 $config['max_size'] = '500';
 $config['max_width']  = '1024';
 $config['max_height']  = '768';

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

 if ( !$this->upload->do_upload())
   {
     $error = array('error' => $this->upload->display_errors());
   } 
 else
   {
     $data = array('upload_data' => $this->upload->data());
   }
}


Several functions needed

$this- > upload- > do_upload(): Perform the operation according to your preference configuration parameters.Note: The file uploaded by default comes from a file field named userfile in the submission form, and the form must be of type multipart.
$this- > upload- > display_errors(): If do_upload() failed to return, displaying error information.This function does not output automatically but returns data, so you can schedule it as you want.
$this- > upload- > data(): This is an auxiliary function that returns an array of all relevant information about the file you uploaded.


Related articles: