从不同输入CakePHP上传图像

时间:2017-06-23 20:54:35

标签: php image cakephp upload cakephp-3.0

我正在尝试从CakePHP上的2个不同输入上传图像。图像上传并保存在特定文件夹中,但当它插入数据库时​​,它只插入1。 我一直在寻找,但一无所获。

控制器:

public function Adicionar()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('POST')) 
    {
        $user = $this->Users->patchEntity($user,$this->request->data());

        $dados=$this->request->data('img');
        move_uploaded_file($dados['tmp_name'], WWW_ROOT . '/img/uploaded/' . $dados['name']);
        $user -> img = 'uploaded/' . $dados['name'];
        //die(debug($user -> img = 'uploaded/' . $dados['name']));


        $dados2=$this->request->data('horario');
        move_uploaded_file($dados2['tmp_name'], WWW_ROOT . '/img/Horarios/' . $dados2['name']);
        $user -> img = 'Horarios/' . $dados2['name'];


        $user->pin = (new DefaultPasswordHasher)->hash($user->pin);
        if($this->Users->save($user))
        {
          $this->redirect(['controller'=>'Users','action'=>'listar']);  
        }
    }
    //die(debug($this->set('user',$user)));
    $this->set('user',$user);
}

查看:

<?=$this->Form->create($user,array('enctype'=>'multipart/form-data'),['role' => 'form']);?>
        <div class="box-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label>Imagem: </label>
                        <div class="input-group">
                            <?=$this->Form->input('img', ['type' => 'file','class' => 'form-control','label' => '']);?>
                            <div class="input-group-addon">
                                <span class="fa fa-file-image-o"></span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>Horário: </label>
                        <div class="input-group">
                            <?=$this->Form->input('horario',['type' => 'file','class' => 'form-control','label' => '']);?>
                            <div class="input-group-addon">
                                <span class="fa fa-calendar"></span>
                            </div>
                        </div>
                    </div>
                    <!-- /.form group -->
                </div>
            </div>  
        </div>

Users database table

1 个答案:

答案 0 :(得分:1)

您没有发布您的用户数据库表,但我认为您的问题是由于以下原因:

您正在使用以下内容更新img字段:

$user -> img = 'uploaded/' . $dados['name'];

然后你用:

覆盖它
$user -> img = 'Horarios/' . $dados2['name'];

因此,您实际上只保存了第二个图像路径。将另一个字段添加到数据库表并在新字段中保存第二个图像路径,或者创建用于存储图像路径的数据库表,并通过user_id将其与users表连接。