如何在CakePHP 2中同时上传多个文件

时间:2014-04-09 05:08:44

标签: cakephp cakephp-2.4

我有一个在CakePHP 2上传图像的功能。它工作正常,但只能同时上传1个文件。如何同时上传多个图像。抱歉我的英文!

控制器

  public function add() {
        $this->set('title_for_layout', 'File');
        $this->loadModel('File');

        if(!empty($this->data)){
        $data = $this->data;

        $file = $data['File']['filename'];


        if($file['name'] != null){
            $data = $this->data;   
            $file =  $data['File']['filename'];
            move_uploaded_file($file['tmp_name'], WWW_ROOT . 'uploads/' . $file['name']);
            $data['File']['title'] = $this->data['File']['title'];
            $data['File']['description'] = $this->data['File']['description'];
            $data['File']['filename'] = $file['name'];
            $this->File->save($data,false);
            $this->Session->setFlash(__('Added.', true));
            $this->redirect(array('action'=>'file'));
        }else{

            $this->Session->setFlash(__('Wrong', true));
            $this->redirect(array('action'=>'file'));
        }
        }
}

查看

<?php echo $this->Form->input('filename', array('type' => 'file')); ?>

感谢。

2 个答案:

答案 0 :(得分:0)

对不起延迟回答。

基本结构如下:

查看:

<?php echo $this->Form->create('Model',  array('type'=>'file')); ?>
<?php echo $this->Form->input('image.0', array('type' => 'file')); ?>
<?php echo $this->Form->input('image.1', array('type' => 'file')); ?>
<?php echo $this->Form->input('image.2', array('type' => 'file')); ?>
<?php echo $this->Form->input('image.3', array('type' => 'file')); ?>
<?php echo $this->Form->end('Save All');

<强>控制器:

function index()
{    
   if($this->request->is('post', 'put'))
   {
       $this->Model->saveAll($this->request->data['image']);
   }
}

<强>型号:

function beforeSave()
{
    foreach($this->data as $k, $v)
    {
        //code here
    }
}

答案 1 :(得分:0)

试试这个:

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

然后,您可以循环访问files数组并像往常一样在控制器函数内处理它们。 查看CakeBakery.