Phalcon hasFiles()总是返回true

时间:2017-09-05 09:20:20

标签: php file-upload phalcon

true条件检查为if时,

文件上传功能始终返回if ($this->request->hasFiles() == true);即使没有上传任何文件。

当表单为空时,将消息显示为:

  

不支持文件格式

注意: 但上传图片时工作正常。

使用HTML创建

Phalcon tag表单。以下是controller的功能,并使用volt显示form

控制器:

function imageupload()
{
    if ($this->request->hasFiles() == true)
    {
        $upload_dir = BASE_PATH . '/files/';
        foreach ($this->request->getUploadedFiles() as $file) {
            if($file->getSize()>1000000)
            {
                $this->flash->error("File too big");
                return  false;
            }
            if(!in_array($file->getRealType(),array('image/jpg','image/jpeg','image/png','image/gif')))
            {
                $this->flash->error("File format not supported");
                return  false;
            }
            if($file->isUploadedFile())
            {
                $filename=rand().'_'.date('Ymdhis').'.'.$file->getExtension();
                $file->moveTo($upload_dir . $filename);
                return $filename;
            }
            else
            {
                $this->flash->error($file->getError());
                return  false;
            }
        }
    }
    return true;
}

查看:

        <?php
    echo $this->tag->form(['company/create','enctype'=>'multipart/form-data']);
    ?>
    <p>
        <label for="name">Name</label>
        <?php echo $this->tag->textField("name"); ?>
    </p>
    <p>
        <label for="logo">Logo</label>
        <?php echo $this->tag->fileField("logo"); ?>
    </p>
    <p>
    <p>
        <?php echo $this->tag->submitButton("Create"); ?>
    </p>
    <?php $this->tag->endForm(); ?>

呼叫上传功能:

<?php
    $logoname=$this->imageupload();
    if($logoname==false)
    {
        $this->dispatcher->forward(['action' => 'new']);
    }
    else
    {   
        ......
        ....
        $success = $form->save();
        if($success)
        {
            $this->flash->success("Company successfully saved!");
            $this->dispatcher->forward(['action' => 'index']);
        }
        else
        {
            $this->flash->error("Following Errors occured:");
            foreach($company->getMessages() as $message)
            {
                $this->flash->error($message);
            }
            $this->dispatcher->forward(['action' => 'new']);
        }
    }
    ?>

1 个答案:

答案 0 :(得分:1)

修改if条件,如下所示:

if ($this->request->hasFiles(true) == true)