Question

I am trying to get my app to be able to handle uploads. This is the add action in DealsController.php.

<?php
        public function add() {
        if ($this->request->is('post')) {
            $this->request->data['Deal']['user_id'] = $this->Auth->user('id');
            $this->Deal->create();
            if ($this->Deal->uploadFile($this->request->data['Deal']['pic'])){
                $file = $this->request->data['Deal']['pic'];
                $this->request->data['Deal']['pic'] = $this->request->data['Deal']['pic']['name'];
                if ($this->Deal->save($this->request->data)) {
                    $this->Session->setFlash(__('Your deal has been saved. %s', h(serialize($file)) ));
                    return $this->redirect(array('action' => 'index'));
                }
                $this->Session->setFlash(__('Unable to add your deal. %s', h(serialize($file)) ));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to upload the file. Please try again. %s', h(serialize($this->request->data['Deal']['pic']))));
        }
    }

The uploadFile function is defined in the model in Deal.php

<?php
public function uploadFile( $check ) {

    $uploadData = array_shift($check);

    if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) {
        return false;
    }

    $uploadFolder = 'files'. DS .'your_directory';
    $fileName = time() . '.pdf';
    $uploadPath =  $uploadFolder . DS . $fileName;

    if( !file_exists($uploadFolder) ){
        mkdir($uploadFolder);
    }

    if (move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
        $this->set('pic', $fileName);
        return true;
    }

    return false;
}

`uploadFile` keeps returning false and I get my 

Unable to upload the file. Please try again. a:5:{s:4:"name";s:7:"012.PDF";s:4:"type";s:15:"application/pdf";s:8:"tmp_name";s:14:"/tmp/phpw0uVGS";s:5:"error";i:0;s:4:"size";i:70118;}

flash. Which is confusing, since it makes it look like the file was actually uploaded to a temp dir. I tried different paths for move_uploaded_file but nothing worked. Does this have something to do with file permissions? It couldn't be file-size, since my upload file was only about 80 KB.

Was it helpful?

Solution

Solution: Don't try to code it yourself. Use one of the already existing file upload plugins for CakePHP, which will handle all the ins and outs behind the scenes, with minimal coding on your part.

I personally use https://github.com/josegonzalez/upload

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top