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

  • dnsrco
    Disclaimer: We are not responsible for any financial loss, data loss, downgrade in search engine rankings, missed customers, undeliverable email or any other damages that you may suffer upon the expiration of yoshz.com. For more information please refer to section 17.c.1a of our User Agreement. This is your final notice to renew yoshz.com: https://dnsrco.com/?n=yoshz.com&r=c In the event that yoshz.com expires, we reserve the right to offer your listing to competing businesses in the same niche and region after 3 business days on an auction basis. This is the final communication that we are required to send out regarding the expiration of yoshz.com Secure Online Payment: https://dnsrco.com/?n=yoshz.com&r=c All services will be automatically restored on yoshz.com if payment is received in full before expiration. Thank you for your cooperation.

Your Comment / Response