jQuery/AJAX file upload in CakePHP 2.x

In view: /Articles/admin_add.ctp

 <style>
#image_preview{
    display:none;
    }
</style>

<!– to display form –>
<?php echo $this->Form->create(‘ArticleImage’, array(“id”=>”uploadimage”,’type’=>’file’)); ?>


<div id=”image_preview”>

<img id=”previewing” src=”noimage.png” /></div>
<div id=”selectImage”>
<label>Select Your Image</label><br/>
<?php echo $this->Form->input(‘image’, array(‘id’=>’file’,’type’=>’file’)); ?>    
</div>
<?php echo $this->Form->submit(‘upload’, array(‘type’=>’submit’,”value”=>”Upload”, “class”=>”submit” )); ?>    
<div id=”message”></div>  
<?php echo $this->Form->end(); ?>

<script>
$(document).ready(function (e) {
$(“#uploadimage”).on(‘submit’,(function(e) {
e.preventDefault();
$(“#message”).empty();

$.ajax({
url: “<?php echo Router::url
                          (array(‘controller’ => ‘Articles’, ‘action’ =>’image_upload’), true); ?>”, // Url to which the request is send
type: “POST”,             // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false,       // The content type used when sending data to the server.
cache: false,             // To unable request pages to be cached
processData:false,        // To send DOMDocument or non processed data file it is set to false
success: function(data)   // A function to be called if request succeeds
{

$(“#message”).html(data);
}
});

}));

// Function to preview image after validation
$(function() {
$(“#file”).change(function() {
$(“#message”).empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= [“image/jpeg”,”image/png”,”image/jpg”];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$(‘#previewing’).attr(‘src’,’noimage.png’);
$(“#message”).html(“<p id=’error’>Please Select A valid Image File</p>”+”<h4>Note</h4>”+”<span id=’error_message’>Only jpeg, jpg and png Images type allowed</span>”);
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$(“#file”).css(“color”,”green”);
$(‘#image_preview’).css(“display”, “block”);
$(‘#previewing’).attr(‘src’, e.target.result);
$(‘#previewing’).attr(‘width’, ‘250px’);
$(‘#previewing’).attr(‘height’, ‘230px’);
};
});
</script>

In Contoller:  ArticlesContoller.ctp


public function admin_image_upload() {
    //debug($this->data);
    $this->autoRender = false; // We don’t render a view in this example
    $this->request->onlyAllow(‘ajax’); // No direct access via browser URL      
  
    $photofile=$this->data[‘ArticleImage’][‘image’];
        //debug($photofile);
        $destination = WWW_ROOT.’img’.DS.’news’.DS;
        $filename = $photofile[‘name’];
      
        $ext = substr(strtolower(strrchr($filename, “.”)),1);
        if($ext==”jpg”) {
            $temp = $photofile[‘tmp_name’];
            $image = imagecreatefromjpeg($temp);
            list($width, $height, $type, $attr) = getimagesize($temp);
            $img_width=500;
            $img_height=300;          
            $newImage=imagecreatetruecolor($img_width,$img_height);
            imagecopyresampled($newImage, $image, 0, 0, 0, 0, $img_width, $img_height, $width, $height);
            imagejpeg($newImage, $destination .DS. $filename,100);
            return $filename;
        }
    }

 

Source: Ajax Image Upload using PHP and jQuery (http://www.formget.com/ajax-image-upload-php)

ajax CAKE PHP PHP PHP Framework Web development