Monday, May 16, 2022

How to Create Drag n Drop File Upload in CodeIgniter 4

 On this simple tutorial, we gonna make a file upload with drag n drop features. We will using CodeIgniter 4 framework and Dropzone.js library.

Preparation

you're have running codeigniter 4 environment ready to used


Step 1. Enable CSRF in Codeigniter 4


Open .env file. Remove # from the start of the security.tokenName, security.headerName, security.cookieName, security.expires, and security.regenerate. Using security.tokenName read CSRF hash. You can update it with any other value.
# security.csrfProtection = 'cookie'
# security.tokenRandomize = false
security.tokenName = 'csrf_token_name'
security.headerName = 'X-CSRF-TOKEN'
security.cookieName = 'csrf_cookie_name'
security.expires = 7200
security.regenerate = true
# security.redirect = true
# security.samesite = 'Lax'
Open app/Config/Filters.php file. Uncomment in 'csrf' in 'before' if commented.
public $globals = [
    'before' => [
        // 'honeypot',
        'csrf',
        // 'invalidchars',
     ],
     'after' => [
        'toolbar',
        // 'honeypot',
        // 'secureheaders',
     ],
];
Step 2. Create new Route Open app/Config/Routes.php file. Define 2 routes – / – Display file upload view. page/fileUpload – It is used to upload a file.
$routes->get('/', 'PageController::index');
$routes->post('page/fileUpload', 'PageController::fileUpload');
Step 3. Create the Controller Create PageController Controller –
php spark make:controller PageController
Open app/Controllers/PageController.php file.
setRules([
         'file' => 'uploaded[file]|max_size[file,2048]|ext_in[file,jpeg,jpg,png,pdf],'
      ]);

      if ($validation->withRequest($this->request)->run() == FALSE){

          $data['success'] = 0;
          $data['error'] = $validation->getError('file');// Error response

      }else{

          if($file = $this->request->getFile('file')) {
             if ($file->isValid() && ! $file->hasMoved()) {
                // Get file name and extension
                $name = $file->getName();
                $ext = $file->getClientExtension();

                // Get random file name
                $newName = $file->getRandomName();

                // Store file in public/uploads/ folder
                $file->move('../public/uploads', $newName);

                // Response
                $data['success'] = 1;
                $data['message'] = 'Uploaded Successfully!';

             }else{
                // Response
                $data['success'] = 2;
                $data['message'] = 'File not uploaded.'; 
             }
          }else{
             // Response
             $data['success'] = 2;
             $data['message'] = 'File not uploaded.';
          }
      }
      return $this->response->setJSON($data);

   }

}
4. Create the View Create index.php file in app/Views/. and then Include Dropzone and jQuery library. You can download Dropzone from here or you can use CDN –


Create a hidden element to store CSRF token name specified in .env file in the name attribute and store CSRF hash in the value attribute.

Complete code:




   Drag and Drop file upload with Dropzone in CodeIgniter 4

   
   

   
   
   




    
   

   

0 comments:

Post a Comment