How to upload file in cakephp without refersh page

Here we are going discuss about how to upload image or file without refresh page in cakephp and jquery.

Create controller in cakephp

ProfilesController.php

class ProfilesController extends AppController {
var $name = 'Profiles';
public $uses = array('Profile');
function changeprofilephoto() {
$profile_id =14; //
$path = "../../app/webroot/profilepic/";//set path
$valid_formats = array(".jpg", ".png", ".gif", ".bmp", ".jpeg");//
if($this->data)
{
$this->Profile->set( $this->data );
$name = $this->data["Profile"]['profile_pic']['name'];
$size = $this->data["Profile"]['profile_pic']['size'];
if(strlen($name))
{
$fileExt = substr(strrchr($name, '.'), 0);
if(in_array($fileExt,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = strtotime(date('Y-m-d H:i:s')).$fileExt;
$tmp = $this->data["Profile"]['profile_pic']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$this->Profile->set($this->data);
$this->Profile->id=$profile_id;
$this->Profile->saveField('uploadfoldername',$actual_image_name);
echo ".$actual_image_name."" class="preview">";
$this->Session->write('suc','1');
$this->redirect($_SERVER['HTTP_REFERER']);
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
} else
echo "Please select image..!";
exit;
}
}
}

Create view file

Views/Profiles/changeprofilephoto.ctp

 
echo $this->Html->script('jquery.min.js');
echo $this->Html->script('jquery.form.js');
?>
 


Thanks cheers 🙂

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *

Top