CakePHP 3:上传多个文件并在关联模型中保存文件名?

时间:2015-10-06 22:40:35

标签: cakephp file-upload cakephp-3.0 cakephp-3.1

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

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

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]);

我遇到了问题,并试图了解我犯错误的地方,但没有成功。

PostsController:

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']);
}

PostsTable:

$this->addBehavior('Upload');

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

UploadBehavior

我目前执行调试$ 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']);

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

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

1 个答案:

答案 0 :(得分:0)

我认为你的领域应该是这样的

echo $this->Form->file('photos.name.',['multiple'=>true]); //note dot notation at end of name. It will generate input name as array