【发布时间】:2016-03-23 16:05:42
【问题描述】:
我正在尝试使用 PHP 从控制器上传图像。此处图像上传工作正常,但内容未保存在数据库中,仅保存图像路径。如果我对图像上传代码发表评论,那么内容就会很好地添加到数据库中。
这是我尝试过的代码
<?= $this->Form->create($news,array('type'=>'file')) ?>
<div class="col-md-12">
<?php
echo $this->Form->input('newsImage',['type'=>'file']);
echo $this->Form->input('title',['class'=>'form-control']);
echo $this->Form->input('news');
?>
</div>
<?= $this->Form->end() ?>
在控制器中,我尝试了以下代码来上传图片
if ($this->request->is('post')) {
$target_dir = "img/news/";
$target_file = $target_dir . basename($_FILES["newsImage"]["name"]);
$fNAME = $_FILES["newsImage"]["name"];
$TMPNAME = $_FILES['newsImage']['tmp_name'];
move_uploaded_file($_FILES["newsImage"]["tmp_name"], $target_file);
$this->request->data['News']['newsImage']=$fNAME;
$news = $this->News->patchEntity($news, $this->request->data);
if ($this->News->save($news)) {
$this->Flash->success(__('The news has been saved.'));
//return $this->redirect($this->referer());
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The news could not be saved. Please, try again.'));
}
}
这里只有图片目录保存在数据库中,标题和新闻不保存。
【问题讨论】:
-
我认为您不希望数据中有
['News']级别。查看$this->request->data的内容并将您创建的字段与该格式匹配。
标签: cakephp cakephp-3.0 cakephp-3.1