我想在我的cakephp 3.0應用中上傳圖片。但我收到錯誤消息:cakePHP 3.0上傳圖片
Notice (8): Undefined index: Images [APP/Controller/ImagesController.php, line 55]
在cakePHP 3.0中是否已經有一些上傳文件(多個文件)的例子?因爲我只能找到CakePHP 2.x的示例!
我想我需要在我的ImagesTable.php中添加自定義驗證方法?但我無法讓它工作。
ImagesTable
public function initialize(array $config) {
$validator
->requirePresence('image_path', 'create')
->notEmpty('image_path')
->add('processImageUpload', 'custom', [
'rule' => 'processImageUpload'
])
}
public function processImageUpload($check = array()) {
if(!is_uploaded_file($check['image_path']['tmp_name'])){
return FALSE;
}
if (!move_uploaded_file($check['image_path']['tmp_name'], WWW_ROOT . 'img' . DS . 'images' . DS . $check['image_path']['name'])){
return FALSE;
}
$this->data[$this->alias]['image_path'] = 'images' . DS . $check['image_path']['name'];
return TRUE;
}
ImagesController
public function add()
{
$image = $this->Images->newEntity();
if ($this->request->is('post')) {
$image = $this->Images->patchEntity($image, $this->request->data);
$data = $this->request->data['Images'];
//var_dump($this->request->data);
if(!$data['image_path']['name']){
unset($data['image_path']);
}
// var_dump($this->request->data);
if ($this->Images->save($image)) {
$this->Flash->success('The image has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The image could not be saved. Please, try again.');
}
}
$images = $this->Images->Images->find('list', ['limit' => 200]);
$projects = $this->Images->Projects->find('list', ['limit' => 200]);
$this->set(compact('image', 'images', 'projects'));
$this->set('_serialize', ['image']);
}
圖片add.ctp
<?php
echo $this->Form->input('image_path', [
'label' => 'Image',
'type' => 'file'
]
);
?>
圖片實體
protected $_accessible = [
'image_path' => true,
];
嘿,請幫忙嗎?我已經安裝了上述內容,完全按照文檔中的說法進行,但不會上傳文件或將文件名存儲到數據庫。有任何想法嗎? – Deej
請通過gitter.im/bobmulder與我聯繫,並分享一些代碼.... – Bob
@SyamsoulAzrien你應該問一個新問題:-) – Spriz