Pergunta

I'm new to cake PHP and I need some help with uploading an image. I need to allow a user to upload an image and I want that image to be saved in the directory(www/CakePHP/app/webroot/img/), and also would like the database to store the file path of the image. This is what I have got so far,

ProductsADD.ctp:

<div class="products form">
<?php echo $this->Form->create('Product'); ?>


    <fieldset>
        <legend><?php echo __('Add Product Details'); ?></legend>
    <?php
        echo $this->Form->input('product_name', array('required'=>false));
        echo $this->Form->input('product_model_number', array('required'=>false));
        echo $this->Form->input('product_brand', array('required'=>false));
        echo $this->Form->input('product_description', array('required'=>false));
        echo $this->Form->input('price_bronze', array('required'=>false));
        echo $this->Form->input('price_silver', array('required'=>false));
        echo $this->Form->input('price_gold', array('required'=>false));
        echo $this->Form->input('upload', array('type'=>'file'));


    ?>
    </fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

productscontroller:

   public function add() {
            if ($this->request->is('post')) {
                $this->Product->create();
                if ($this->Product->save($this->request->data)) {
                    $this->Session->setFlash(__('The product has been saved.'));
                    return $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
                }
                if(!empty($this->data))
                {
                    //Check if image has been uploaded
                    if(!empty($this->data['products']['upload']['name']))
                    {
                        $file = $this->data['products']['upload']; //put the data into a var for easy use

                        $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                        $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

                        //only process if the extension is valid
                        if(in_array($ext, $arr_ext))
                        {
                            //do the actual uploading of the file. First arg is the tmp name, second arg is
                            //where we are putting it
                            move_uploaded_file($file['tmp_name'], WWW_ROOT . 'CakePHP/app/webroot/img/' . $file['name']);

                            //prepare the filename for database entry
                            $this->data['products']['product_image'] = $file['name'];
                        }
                    }

                    //now do the save
                    $this->products->save($this->data) ;
                }
            }

        }

I can't seem to figure out why the uploaded image does not get saved to the directory. Can someone please help.

Foi útil?

Solução

While creating new form in cakephp with file input, you have to set 'enctype'=>'multipart/form-data'

code should be like this :

<?php echo $this->Form->create('Product',array('enctype'=>'multipart/form-data')); ?>

i hope this will works

Outras dicas

You're missing the multipart in the form, instead:

<?php echo $this->Form->create('Product'); ?>

try that

<?php echo $this->Form->create('Product', array('type' => 'file); ?>

Change this

<?php echo $this->Form->create('Product'); ?>

to

<?php $this->Form->create('Product',array('type'=>'file')); ?>

Here is what I used for cakephp 2.7.2

public function add() {
    if ($this->request->is('post')) {
        $this->Category->create();
        //Check if image has been uploaded
        if (!empty($this->request->data['Category']['upload']['name'])) {
            $file = $this->request->data['Category']['upload'];

            $ext = substr(strtolower(strrchr($file['name'], '.')), 1);
            $arr_ext = array('jpg', 'jpeg', 'gif','png');

            if (in_array($ext, $arr_ext)) {
                move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/webimages/categories/' . $file['name']);
                //prepare the filename for database entry
                $this->request->data['Category']['image'] = $file['name'];
            }
        }

        if ($this->Category->save($this->request->data)) {
            $this->Session->setFlash(__('The category has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The category could not be saved. Please, try again.'));
        }
    }
    $parentCategories = $this->Category->ParentCategory->find('list');
    $categoriesStatus = $this->Category->getCategoriesStatus();//model's method to get list of status
    $this->set(compact('parentCategories', 'categoriesStatus'));
}

Note: actual field in db was image but I changed it to upload then in controller I added upload file name to image and then saved in db.

Here's what worked for me

     public function add() {
    if ($this->request->is('post')) {

      //Check if image was sent
      if(!empty($this->request->data['Post']['upload']))
      {
        $file = $this->request->data['Post']['upload']; // Creating a variable to handle upload
        debug($file);
        $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
        $arr_ext = array('jpg', 'jpeg', 'gif', 'png'); //processing file extension

        //if extension is valid
        if(in_array($ext, $arr_ext))
        {
          //do the actual uploading of the file. First arg is the tmp name, second arg is
          //where we are putting it
          move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . $file['name']);

          //saving file on database
          $this->request->data['Post']['upload'] = $file['name'];
        }
      }

      //now do the save
      if ($this->Post->save($this->request->data)) {
        $this->Flash->success('Your post has been saved with image.');
        $this->redirect(array('action' => 'index'));
      }else {

      }
    }
  }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top