CakePHP Upload Multiple File Component


This Upload Component will upload any file (docs, photo) and rename the filename to prevent the duplicate filename.

In UploadComponent.php

class UploadComponent extends Component {
    var $name = 'Upload';
    function upload(){
      $target_dir = WWW_ROOT . "files/";
      $filename = $this->rename($files['name']);
      $target_file = str_replace('//','/',$target_dir) . $filename;

      if(move_uploaded_file($files["tmp_name"], $target_file)){
         return $filename;
      } else {
         return $uploadKO;
      }
    }

    function rename($fname){
        $imageFileType = pathinfo($fname,PATHINFO_EXTENSION);
        $filename = String::uuid();
        settype($filename, 'string');
        $filename = $filename.'.'.$imageFileType;
       
        return $filename;
    }

    function delete($fname){
        $target_dir = WWW_ROOT . "files/";
        $uploadKO = 0;
       
        if(!unlink($target_dir.$fname)){
            $uploadKO = 1;
        }

        return $uploadKO;
    }
}

In PostsController.php

function upload(){
   $files = $this->request->data['Post']['files'];

   foreach($files as $files){
       $result = $this->Upload->upload($files);
                   
       if($result != 1){
          //Upload Success
       }
   }
}

In upload.ctp

<?php
echo $this->Form->create('Post',array('type' => 'file'));
echo $this->Form->input('files.', array('type' => 'file', 'multiple'));
echo $this->Form->submit('Upload');
>echo $this->Form->end();
?>

Done!

Comment / Response