Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • how to upload & save images into database In CakePHP

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.76k
    Comment on it

    In this post, I am gonna give an example to upload Images and store its file path in the database with the help of custom component.

    Example:

    Add this UploadComponent class in app/controller/component folder.

     <?php    
    class UploadComponent extends Component {
        public function start_upload($file_Details) {
         //echo "<pre>@@@";
         print_r($file_Details);
            $filename = ($file_Details['name']);
            $filename = time().$filename;
            $file_path =   WWW_ROOT  . 'files/'.$filename;
            move_uploaded_file($file_Details['tmp_name'],$file_path);
            return $filename;
         }
    
          } 
    ?>
    

    Important Syntax Meaning:

    $file_path = WWW_ROOT. 'img'; this will set the webroot path with the folder name where the file is to be uploaded.

    $filename = time().$filename; this syntax will append the random no before the file name so that it wont get conflict from already existing file.


    Add this code in Controller class.

    public function uploadfile() {
    
      $file_name1 = '';
    
      if ($this->request->is('post')) { 
    
      $file_name1=$this->Upload->start_upload($this->data['uploadFile']['pdf_path']);   
    
            $data=array();
            $data['User']['id'] = CakeSession::read("Auth.User.id");
            $data['User']['imagename'] = $file_name1;
            $this->User->save($data);       // save the file path in database
    
            echo $data['User']['id']." + ".$data['User']['imagename'];
             }
    
      $this->set('image',$file_name1); 
    }
    

    Add this code in app/view/users folder & save it as uploadfile.ctp.

    <div class="users view">
    <h2><?php echo('User'); ?></h2>
    <?php
    echo $this->Form->create('uploadFile', array('type' => 'file')); //input field of type file that allows browse your file.
    echo $this->Form->input('pdf_path', array('type' => 'file','label' => 'Pdf'));
    echo $this->Form->end('Upload file');
    $image_src = $this->webroot.'img/'.$image;
    ?>
    <img src="<?php echo $image_src;?>">
    </div>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: