【发布时间】:2017-09-05 09:20:20
【问题描述】:
当检查if条件为if ($this->request->hasFiles() == true)时,文件上传函数总是返回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']);
}
}
?>
【问题讨论】:
-
如果您得到该错误消息,那么
$file->getRealType()必须针对实际对象运行,这意味着getUploadedFiles()正在返回一些东西。是时候开始调试了。 -
@iainn 我的期望是如果文件没有上传,那么
if ($this->request->hasFiles() == true)应该返回 false。我的理解正确吗? -
我不知道 Phalcon 的具体工作原理,但您的期望听起来是正确的。
$this->request->getUploadedFiles()必须返回一个对象数组,如果你的代码表现得像这样的话,所以先看看它返回了什么。
标签: php file-upload phalcon