Wednesday, 19 March 2014

Simplest way to use uploadify with cakephp

I have posted a tutorial on how to use uploadify with cakephp

Users can upload images with uploadify and when uploadify sends the image to my controller I simply attach the sessionid as a parameter.

Step One.
Create function on own controller 
app/controller/PagesController.php

public function index() { /* this function for show index page*/
    $this->layout='home';
        $this->set('title_for_layout', 'Photo Upload');
      
    }
   
    public function uploadify() { /* this function for upload file */
    $this->autoRender=false;
   
         $targetFolder = WWW_ROOT .'/img/';  // this folder created on webroot/
      
         $tempFile = $_FILES['Filedata']['tmp_name'];
       $targetPath = $targetFolder;
    $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
   
    // Validate the file type
    $fileTypes = array('jpg','jpeg','gif','png'); // File extensions
    $fileParts = pathinfo($_FILES['Filedata']['name']);
   
    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($tempFile,$targetFile);
        echo $_FILES['Filedata']['name'];
    } else {
        echo 'Invalid file type.';
    }
      
    }

Step 2
create view file for display 
<h1>Uploadify Demo</h1>
     <?php echo $this->Form->create('Setting', array('url'=>'#','type' => 'file')); ?>
        <div id="queue"></div>
      <?php echo $this->Form->input('file_upload',array('type' => 'file', "id"=>'file_upload', 'div'=>false,'label'=>false,"multiple"=>"true"));?>
<?php echo $this->Form->input('police_no',array('id'=>'police_no', 'div'=>false,'label'=>false));?>
<?php echo $this->Form->button('Submit',array('class'=>'button','div'=>false,'label'=>false));?>
    <script type="text/javascript">
        <?php $timestamp = 'phptp';?>
        $(function() {
            $('#file_upload').uploadify({
                'formData'     : {
                    'test' : '<?php 'photoupload';?>',
                    'token'     : '<?php echo md5('unique_salt' . $timestamp);?>'
                },
                'method'   : 'post',
                 'fileSizeLimit' : '100KB',
                 'fileTypeDesc' : 'Image Files',
                'fileTypeExts' : '*.gif; *.jpg; *.png',
                'debug'    : false,
                'swf'      : '../img/uploadify.swf', /* this file save into webroot/images folder*/
                'uploader' : '../Pages/uploadify', /* this function will come for controller
                'onUploadSuccess' : function(file, data, response) {
                 document.getElementById('police_no').value=data;


        }
            });
        });

No comments:

Post a Comment