我是CakePHP的新手,我现在正在使用这个框架创建一个应用程序我遇到了一些问题,没有上传图像而是将图像名称保存到数据库。在我的代码下面:
public function save()
{
$shop = TableRegistry::get('shop');
$query = $shop->query();
//
$product = $this->request->data('prductname');
$domain = $this->request->data('domainname');
$phone = $this->request->data('phone');
if (!empty($this->request->data))
{
$file = $this->request->data['file'];
}
$filename = $file;
$file_tmp_name = $filename;
$dir = WWW_ROOT.'img'.DS.'uploads';
$allowed = array('png','jpg','jpeg' );
if (!in_array(substr(strrchr($filename,'.'),1),$allowed))
{
throw new InternalErrorException("Error Processing Request", 1);
}
elseif(is_uploaded_file($file_tmp_name))
{
$filename = Text::uuid().'-'.$filename;
$fileDB = TableRegistry::get('shop');
$entity = $fileDB->newEntity();
$entity->filename = $filename;
$fileDB->save($entity);
move_uploaded_file($file_tmp_name, $dir.DS.$filename);
}
$query->insert([
'prductname','domainname','phone','file'
])->values([
'prductname'=>$product,
'domainname'=>$domain,
'phone'=>$phone,
'file' => $file
])->execute();
if ($query)
{
$this->Flash->success('This information has been saved.');
$this->redirect(['controller'=>'shop','action'=>'index']);
}
}
形式:
<?php
echo $this->Form->create(null,['url'=>['controller'=>'Shop', 'action'=>'save']],['enctype' => 'multipart/form-data']);
?>
<div class="form-group">
<label for="product">Product Name</label>
<input type="text" class="form-control" name="prductname" placeholder="Name">
</div>
<div class="form-group">
<label for="domain">Domain Name</label>
<input type="text" name="domainname" class="form-control" placeholder="Domain Name">
</div>
<div class="form-group">
<label for="Phone">Phone</label>
<input type="text" name="phone" class="form-control" placeholder="Phone">
</div>
<div class="form-group">
<label for="InputFile">File input</label>
<input type="file" name="file">
</div>
<button type="submit" class="btn btn-default">Save</button>
<?php
echo $this->Form->end();
?>
不显示任何错误,图像名称保存到DB但未将图像替换为目标文件夹。
谢谢
答案 0 :(得分:0)
我认为$file_tmp_name
对move_uploaded_file
期望的内容可能不正确。 move_uploaded_file
期望$tmp_name
是PHP为每个上传文件分配的唯一字符串。我不确定$this->request->data['file']
具有什么结构,但$_FILES
数组包含数组键,例如'name'
,'size'
,'tmp_name'
和{{ 1}}。您需要使用'type'
中的'tmp_name'
。这可能出现在move_uploaded_file
中,如果是这样,最好使用该数组中的$this->request->data
。