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 "
";
$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
Html->script('jquery.min.js');
echo $this->Html->script('jquery.form.js');
?>
Form->create('Profile',array('id'=>'Profile', 'controller'=>'Profiles','action'=>'changeprofilephoto', 'type'=>'file'));
?>
Change profile image
Upload your image
file('profile_pic', array('id'=>'profile_pic', "label" => false, "div"=>false, 'class'=>'styled-input-big'))?>
Form->end();
?>
Thanks cheers 🙂