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 "<img src='/profilepic/".$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
<?php echo $this->Html->script('jquery.min.js'); echo $this->Html->script('jquery.form.js'); ?> <script type="text/javascript" > $(document).ready(function() { $('#profile_pic').live('change', function(){ $("#preview").html(''); $("#preview").html('<img src="../img/loader.gif" alt="Uploading...."/>');//download loding image $("#Profile").ajaxForm({ target: '#preview' }).submit(); }); }); </script> <style> .preview { width:200px; border:solid 1px #dedede; padding:10px; } #preview { color:#cc0000; font-size:12px } </style> <div class="layout-popup f-left"> <?php echo $this->Form->create('Profile',array('id'=>'Profile', 'controller'=>'Profiles','action'=>'changeprofilephoto', 'type'=>'file')); ?> <!-- start id-form --> <table class="frm-tbl" id="id-form" > <tr> <td colspan="2" class="align-t-r" > <div class="f-left popup-title">Change profile image</div> </td> </tr> <tr> <td>Upload your image</td> <td align="left" > <!-- <input type="file" name="[Profile][photoimg]" id="profile_pic" /> --> <?php echo $form->file('profile_pic', array('id'=>'profile_pic', "label" => false, "div"=>false, 'class'=>'styled-input-big'))?> </td> </tr> <tr> <td colspan="2"> <div id='preview'> </div> </td> </tr> </table> <?php echo $this->Form->end(); ?> </div> |
Thanks cheers 🙂