0

Hi guys I am trying to save an image to filesystem and then save the file path to a database.

My controller

<?php

class ProductsController extends AppController {

    public function add() {
     if ($this->request->is('post')) {
     if (!empty($this->request->data)) {
     $this->Product->create();
     $this->Product->save($this->request->data['post']);
       }
     }  
    }
  }

My view code:

    <div class="add_ondemand">
    <h1>Add Post</h1>
    <?php
    echo $this->Form->create('post');
    echo $this->Form->input('name', array('placeholder'=>'name'));
    echo $this->Form->textarea('description', array('placeholder'=>'description'));
    echo $this->Form->input('director', array('placeholder'=>'director'));
    echo $this->Form->input('cast', array('placeholder'=>'cast'));
    echo $this->Form->input('release_date', array('placeholder'=>'release      date','id'=>'datepicker', 'type'=>'text'));
    echo $this->Form->input('Product.File',array('type' => 'file'));
    echo $this->Form->end('Save Post');
    ?>

</div>



<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>

Any help would be greatly appreciated

1 Answer 1

3

Use this to your Product.php model file.......

public $validate = array(
                    'photo_name' => array(
                        'uploadError' => array(
                            'rule' => 'uploadError',
                            'message' => 'Something went wrong with the file upload',
                            'required' => FALSE,
                            'allowEmpty' => TRUE,
                        ),
                        'photoSize' => array(
                            'rule' => array('fileSize','<=','2MB'),
                            'message' => 'Photo size must be less then 2MB.',
                            'required' => FALSE,
                            'allowEmpty' => TRUE,
                        ),
                        'mimeType' => array(
                            'rule' => array('mimeType', array('image/gif','image/png','image/jpg','image/jpeg')),
                            'message' => 'Invalid file, only images allowed',
                            'required' => FALSE,
                            'allowEmpty' => TRUE
                        ),
                        'processUpload' => array(
                            'rule' => 'processUpload',
                            'message' => 'Something went wrong processing your file',
                            'required' => FALSE,
                            'allowEmpty' => TRUE,
                            'last' => TRUE,
                        )
                    )
            );


public $uploadDir = 'img/user_photos';

/**
 * Process the Upload
 * @param array $check
 * @return boolean
 */
public function processUpload($check=array()) {
    // deal with uploaded file
    if (!empty($check['photo_name']['tmp_name'])) {

        // check file is uploaded
        if (!is_uploaded_file($check['photo_name']['tmp_name'])) {
            return FALSE;
        }

        // build full filename
        $filename = WWW_ROOT . $this->uploadDir . DS . String::uuid().'.'.pathinfo($check['photo_name']['name'], PATHINFO_EXTENSION);

        // @todo check for duplicate filename

        // try moving file
        if (!move_uploaded_file($check['photo_name']['tmp_name'], $filename)) {
            return FALSE;

        // file successfully uploaded
        } else {
            // save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
            $this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT.IMAGES_URL, "", $filename));
        }
    }

    return TRUE;
}

/**
 * Before Save Callback
 * @param array $options
 * @return boolean
 */
public function beforeSave($options = array()) {
    // a file has been uploaded so grab the filepath
    if (!empty($this->data[$this->alias]['filepath'])) {
        $this->data[$this->alias]['photo_name'] = $this->data[$this->alias]['filepath'];
    }       
    return parent::beforeSave($options);
}

public function beforeValidate($options = array()) {
    // ignore empty file - causes issues with form validation when file is empty and optional
    if (!empty($this->data[$this->alias]['photo_name']['error']) && $this->data[$this->alias]['photo_name']['error']==4 && $this->data[$this->alias]['photo_name']['size']==0) {
        unset($this->data[$this->alias]['photo_name']);
    }

    parent::beforeValidate($options);
}

well its not my code and i forget the source where i got it.

Sign up to request clarification or add additional context in comments.

4 Comments

Doesnt work for me... not uploading and the file path isnt being sent to the database
Which Cakephp version you are using? Is there any error message? Try changing as $uploadDir = 'img';
I am using 2.4.6 Stable, no errors whatsoever. That change didnt make a different, I think that is just the directory that the file will be stored. Since the path isnt being saved either I think something else is wrong
I got it... See, I didn't provide you that code just for copy paste. You have to change them as your project. The ['photo_name'] that i used for my project... you have to change them all as ['File'].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.