Array to string Error while uploading an Image

血红的双手。 提交于 2019-12-13 11:10:04

问题


i was trying to upload image using cakephp , i got the following error :

Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1009]

<?php echo $this->Form->create('User',array('type'=>'file')); 
      echo $this->Form->input('profile_pic', array('type'=>'file')); 
      echo $this->Form->end('submit');
?>

anything wrong with what i've did ?


回答1:


You study cakephp manual properly HOW form type can be File ?????? :)

Use this

<?php echo $this->Form->create('User',array('enctype'=>'multipart/form-data')); 
      echo $this->Form->input('profile_pic', array('type'=>'file')); 
      echo $this->Form->end('submit');
?>



回答2:


You need to treat the file upload in the controller. If you debug the request you'll see that profile_pic field is an array:

# in controller:
if ($this->request->is('post')) {
            debug($this->request->data); die();
        }

# result:
array(
    'User' => array(
        'profile_pic' => array(
            'name' => 'wappy500x500.jpg',
            'type' => 'image/jpeg',
            'tmp_name' => '/tmp/phptk28hE',
            'error' => (int) 0,
            'size' => (int) 238264
        )
    )
)

Short answer:

public function upload() {
        if ($this->request->is('post')) {
            if(isset($this->request->data['User']['profile_pic']['error']) && $this->request->data['User']['profile_pic']['error'] === 0) {
                $source = $this->request->data['User']['profile_pic']['tmp_name']; // Source
                $dest = ROOT . DS . 'app' . DS . 'webroot' . DS . 'uploads' . DS;   // Destination
                move_uploaded_file($source, $dest.'your-file-name.jpg'); // Move from source to destination (you need write permissions in that dir)
                $this->request->data['User']['profile_pic'] = 'your-file-name.jpg'; // Replace the array with a string in order to save it in the DB
                $this->User->create(); // We have a new entry
                $this->User->save($this->request->data); // Save the request
                $this->Session->setFlash(__('The user has been saved.')); // Send a success flash message
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }

        }
    }

Of course you need to make extra validations on the uploaded file.

Further reading: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+cakephp+upload+file



来源:https://stackoverflow.com/questions/26234304/array-to-string-error-while-uploading-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!