我正在尝试使用cakephp 3上传图像。我在蛋糕 2.x 中尝试过,它在那里工作正常,但在蛋糕 3.0 中效果不佳。我的图像已上传,但未保存在数据库中。
视图
<div class="col-lg-8">
<div class="articles form large-9 medium-8 columns content">
<?= $this->Form->create($article,['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add Article') ?></legend>
<?php
echo $this->Form->input('title', [ "class" => "form-control"]);
echo $this->Form->input('body', [ "class" => "form-control"]);
echo $this->Form->file('image',[ "class" => "form-control"]);
?>
</fieldset>
<?= $this->Form->button(__('Submit'), ["class" => "btn btn-primary"]) ?>
<?= $this->Form->end() ?>
</div>
控制器
public function add() {
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$filepath = getcwd() . '/uploads/' . $this->request->data['image']['name'];
$filename = $this->request->data['image']['name'];
$article = $this->Articles->patchEntity($article, $this->request->data);
if ($this->Articles->save($article)) {
move_uploaded_file($this->request->data['image']['tmp_name'], $filepath);
$this->Flash->success(__('The article has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The article could not be saved. Please, try again.'));
}
}
$this->set(compact('article'));
$this->set('_serialize', ['article']);
}
型
namespace App'Model'Table;
use App'Model'Entity'Article;
use Cake'ORM'Query;
use Cake'ORM'RulesChecker;
use Cake'ORM'Table;
use Cake'Validation'Validator;
类 文章表 扩展表
{ 公共函数初始化(数组 $config) { 父::初始化($config);
$this->table('articles');
$this->displayField('title');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Comments', [
'foreignKey' => 'article_id'
]);
}
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->allowEmpty('title');
$validator
->allowEmpty('body');
$validator
->add('image', [
'fileSize' => [
'rule' => [
'fileSize', '<', '5MB'
],
'message' => 'Please upload file smaller than 5MB'
],
'mimeType' => [
'rule' => [
'mimeType', ['image/jpeg','image/png','image/jpg']
],
'message' => 'Please upload only png images'
]
]
)
->requirePresence('image', 'create')
->notEmpty('image');
return $validator;
}
}
我自己找到了解决方案,但我不确定这是否是正确的方法。但是通过这样做,我的问题已经解决了。
public function add() {
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$imageName = $this->request->data['image']['name'];
$filepath = getcwd() . '/uploads/' . $imageName;
$article = $this->Articles->patchEntity($article, $this->request->data);
$article->image = $imageName ;
if ($this->Articles->save($article)) {
move_uploaded_file($this->request->data['image']['tmp_name'], $filepath);
chmod($filepath, 0777);
$this->Flash->success(__('The article has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The article could not be saved. Please, try again.'));
}
}
$this->set(compact('article'));
$this->set('_serialize', ['article']);
}