How to upload files or images in CodeIgniter 4

The upload process consists of the process of uploading files from a local device to a remote server that consists of two steps:

  1. The file to be uploaded is selected and then sent to the server.
  2. The server receives the file and stores it in a specific location.

In a web app, the upload process can be done by implementing an HTML form using the famous HTML file type field or by plugins that send HTTP requests.

The CodeIgniter 4 process for uploading files in English can be divided into the following blocks:

  • Check the uploaded file request
  • Check if it is valid and if it can be moved
  • Validate that the file meets your criteria, for example, if it is an image, a word document... or any other
  • Handle the upload process or error; for this we move it to some folder of our project that is generally the writeable folder or it can be another like the public folder
  • Finally we show the errors if we have errors or we save any reference to the image or file loaded in our database through some model; that is, through a conditional we do one operation or another depending on the server's response:
private function _upload($id)
{
 
 if($imageFile = $this->request->getFile('image')){
  
  if($imageFile->isValid() && !$imageFile->hasMoved()){
   
   // validaciones
   $validated = $this->validate([
    'image' => [
     'uploaded[image]',
     'mime_in[image,image/jpg,image/gif,image/png]'
    ]
   ]);
   if($validated){
    echo "ok";
    $newName = $imageFile->getRandomName();
    //$imageFile->move(WRITEPATH . 'uploads/avatar/', $newName);
    $imageFile->move(ROOTPATH.'public/uploads', $newName);
    $personModel = new PersonModel();
    $personModel->update($id, [
     'image' => $newName
    ]);
    
    return null;
    
   }else {
    return $this->validator->getError("image");
   }

  }
 }
}

This function returns null if the upload was successful or the first error that occurred in the upload process.

And here I show you how you can consume the upload function that we generated earlier through the create and edit processes that are part of our CRUD in CodeIgniter 4.

First, the process of creating in which we insert the data into our database through our model and THEN we upload the file by passing the ID of what we previously created; you can also see the branch we do with the conditionals, in which we only call the upload process when we create the record, otherwise we display the errors. If we create the person and we have problems with the upload function, we send it directly to the edit page and show the errors of the image upload process:
 

public function create()
{
 $person = new PersonModel();
 if ($this->validate('person')) {
  $id = $person->insert(
   [
    'name' => $this->request->getPost('name'),
    'surname' => $this->request->getPost('surname'),
    'age' => $this->request->getPost('age'),
    'description' => $this->request->getPost('description'),
   ]
  );
  $res = $this->_upload($id);
  if($res == null) {
   return redirect()->to('/person')->with('message', 'Persona creada exitosamente' );
  }else{
   return redirect()->to("/person/$id/edit")->withInput();
  }
  return redirect()->to('/person')->with('message', 'Persona creada exitosamente');
 }
 // tenemos problemas con las validaciones
 return redirect()->back()->withInput();
}

public function update($id)
{
 $personModel = new PersonModel();
 $person = $personModel->asObject()->find($id);
 if ($person == null) {
  throw PageNotFoundException::forPageNotFound();
 }
 if ($this->validate('person')) {
  $personModel->update(
   $id,
   [
    'name' => $this->request->getPost('name'),
    'surname' => $this->request->getPost('surname'),
    'age' => $this->request->getPost('age'),
    'description' => $this->request->getPost('description'),
   ]
  );
  $res = $this->_upload($id);
  if($res == null) {
   return redirect()->to('/person')->with('message', 'Persona actualizada exitosamente: ' . $person->name);
  }
  return redirect()->back()->withInput();
 }
 // tenemos problemas con las validaciones
 //return redirect()->back()->withInput();
}

As you can see, we call the _upload function when we already have a reference to the created resource, which in this case would be a person.

You can find the rest of the application code in my github repository as the views used, as well as the routes used.

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.