0

我需要创建上传过程,用户可以使用带有 html5 多个属性的文件字段一次上传多个文件。文件名必须保存在关联模型中。

我可以成功运行上传一个文件并将文件名保存在照片表中,跨字段:

echo $this->Form->file('photos.name');

但是,如果我想启用上传更多照片

echo $this->Form->input('title'); // post title
echo $this->Form->input('maintext'); // post main text,
... etc
echo $this->Form->file('photos[].name',['multiple'=>true]);

我陷入了这个问题,并试图了解我在哪里犯了错误,但没有成功。

帖子控制器:

public function add()
{
    $post = $this->Posts->newEntity();
    if ($this->request->is('post')) {
        $post = $this->Posts->patchEntity($post, $this->request->data);

        if ($this->Posts->save($post)) {
            $this->Flash->success(__('The post has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The post could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('post'));
    $this->set('_serialize', ['post']);
}

帖子表:

$this->addBehavior('Upload');

$this->hasMany('Photos', [
    'foreignKey' => 'post_id'
]);

上传行为

我目前执行调试 $data / $entity 的所有标准回调,但仅在beforeMarshal 我使用:

$data = Hash::get($data,'name');
debug($data);
// debug output
[
'name' => 'HPIM3869.JPG',
'type' => 'image/jpeg',
'tmp_name' => 'C:\xampp\tmp\phpF02D.tmp',
'error' => (int) 0,
'size' => (int) 1295448
],
...

在 beforeSave 和 afterSave

我的表单没问题,数据在 Marshal 方法之前正确输入,如果我上传 3 个文件,我也会看到相同数量的调试输出,但在 beforSave 和 afterSave 调试中只显示第一个文件,如下所示:

debug($entity);

object(App\Model\Entity\Photos) {

    'name' => [
        'name' => 'HPIM3435.JPG',
        'type' => 'image/jpeg',
        'tmp_name' => 'C:\xampp\tmp\php5839.tmp',
        'error' => (int) 0,
        'size' => (int) 1517410
    ],
    'post_id' => (int) 469,
    'created' => object(Cake\I18n\Time) {

        'time' => '2015-10-07T09:22:44+0200',
        'timezone' => 'Europe/Berlin',
        'fixedNowTime' => false

    },
    'modified' => object(Cake\I18n\Time) {

        'time' => '2015-10-07T09:22:44+0200',
        'timezone' => 'Europe/Berlin',
        'fixedNowTime' => false

    },
    '[new]' => true,
    '[accessible]' => [
        '*' => true
    ],
    '[dirty]' => [
        'name' => true,
        'post_id' => true,
        'created' => true,
        'modified' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[repository]' => 'Photos'

}

编辑:

为了测试的目的,我创建了这样一个表格:

echo $this->Form->input('name',['value'=>'zzz']);
echo $this->Form->input('photos.0.name',['value'=>'zzz']);
echo $this->Form->input('photos.1.name',['value'=>'hhh']);
echo $this->Form->input('photos.2.name',['value'=>'fff']);

此外,它只保存第一个结果。

我需要帮助来了解如何保存多个表单数据。我哪里错了?

4

1 回答 1

0

我觉得你的领域应该是这样的

echo $this->Form->file('photos.name.',['multiple'=>true]); //note dot notation at end of name. It will generate input name as array
于 2015-10-07T05:42:55.507 回答