CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New
Need a Website Or Web Application Contact : +91 9437911966 (Whatsapp) Note: Paid Service

How to upload file using Codeigniter 4


contact.php

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\ContactModel;
class Contact extends BaseController
{
public function __construct(){
    }
public function index()
    {    
         return view('form');
    }
public function upload()
    {  
 
        helper(['form', 'url']);
         
        $db = \Config\Database::connect();
         $builder = $db->table('file');
 
        $validated = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[file,image/jpg,image/jpeg,image/gif,image/png]',
                'max_size[file,4096]',
            ],
        ]);
 
        $msg = 'Please select a valid file';
 
        if ($validated) {
            $avatar = $this->request->getFile('file');
            $avatar->move(WRITEPATH . 'uploads');
 
          $data = [
 
            'name' =>  $avatar->getClientName(),
            'type'  => $avatar->getClientMimeType()
          ];
 
          $save = $builder->insert($data);
          $msg = 'File has been uploaded';
        }
 
        return redirect()->to( base_url('contact/form') )->with('msg', $msg);
 
    }
}

form.php

<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 4 Image upload example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
 <div class="container">
    <br>
    <div class="row">
<div class="col-md-4">
   <?php if (session('msg')) : ?>
        <div class="alert alert-success alert-dismissible">
            <?= session('msg') ?>
            <button type="button" class="close" data-dismiss="alert"><span>×</span></button>
        </div>
        <?php endif ?>
        <form action="<?php echo base_url('contact/upload');?>" name="ajax_form" id="ajax_form" method="post" accept-charset="utf-8" enctype="multipart/form-data">
 
          <div class="form-group">
            <label for="formGroupExampleInput">Name</label>
            <input type="file" name="file" class="form-control" id="file" style="height:35px;">
          </div>
 
          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
         
</form>
</div>
 
    </div>
 
</div>
</body>