"Notice: Array to string conversion" 在 CakePHP 中上传文件时

"Notice: Array to string conversion" in CakePHP when uploading a file

我在使用表单时遇到了一些问题,这让我抓狂。

每当我尝试将图像上传到我的数据库时,我得到

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

我不确定自己做错了什么或遗漏了什么。感谢任何帮助。

这是我的模特

        'banner_image' => array(
        'not_required' => array(
            'allowEmpty' => true,
            'required' => false,
        ),
        'is_image' => array(
            'rule' => 'is_image_check',
            'message' => 'We found that the file you uploaded is not an image.',
            //'allowEmpty' => false,
            'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
),

这是我的控制器

/**
 * admin_add method
 *
 * @return void
 */
public function admin_add() {
    if ($this->request->is('post')) {
        $this->Survey->create();
        if ($this->Survey->save($this->request->data)) {
            $this->Session->setFlash(__('The survey has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The survey could not be saved. Please, try again.'));
        }
    }
}

这是我的表格

<?php echo $this->Form->create('Survey', array('type'=>'file')); ?>
<fieldset>
    <legend><?php echo __('Admin Add Survey'); ?></legend>
<?php 
    echo $this->Form->input('title');
    echo $this->Form->input('subtitle');

    if ( empty($this->request->data['Survey']['banner_image']) or isset($this->validationErrors['Survey']['banner_image']) ): 

            echo $this->Form->input('banner_image', array('type'=>'file'));

    else : 

        echo $this->Html->image('/img/surveys/' . $this->request->data['Survey']['banner_image'] ) ;                
        echo $this->Html->link('Remove this image?', '/admin/Surveys/remove_image/' . $this->request->data['Survey']['id'] ) ;
    endif;
    // echo $this->Form->input('listing_image', array('type'=>'file'));
    echo $this->Form->input('url_iframe');
    echo $this->Form->input('enable');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>

这是您的控制器收到的字段 banner_image:

$this->request->data['Survey']['banner_image'] = array(
    'name' => 'example_image.jpg',
    'type' => 'image/jpg',
    'tmp_name' => 'C:/WINDOWS/TEMP/php1EE.tmp', //path will vary on Unix-like OSes
    'error' => 0,
    'size' => 41737,
);

如果您尝试将此保存到您的 table,您将得到

Notice: Array to string conversion in filename on line X

因此,你必须做一些pre-processing才能调用save()

您的 surveys.banner_image 可能设置为接受文件名。

一种典型的方法是实现 Survey::beforeSave() 回调并添加必要的代码以将上传的文件从其临时位置移动到您选择的目标文件夹。

然后用 $data['Survey']['banner_image']['name'] 覆盖 $data['Survey']['banner_image'] 数组。

或者,您可以使用处理上传的多个 CakePHP 插件之一,而不是重新发明轮子,例如 josegonzalez/cakephp-upload

如需进一步参考,请参阅: