我是CakePHP的新手,并且正在使用CakePHP 2x。我正在做一个项目,用户可以使用帖子上传多个图像。到目前为止,我无法上传文件。
这是我数据库的图像表:
post_id
是外键。这是帖子模型:
<?php
class Post extends AppModel {
// The $validate array tells CakePHP how to validate your data when the save() method is called
public $belongsTo = array('Catagory','User');
public $hasMany = array(
'Image' => array(
'className' => 'Image',
'foreignKey' => 'post_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
现在是Post控制器:
public function addPost() {
if ($this->request->is('post')) {
// pr ($this->request->data);
//die();
$rootfolder = WWW_ROOT . 'img/uploads/' ;
if(!empty($this->request->data))
{
//Check if image has been uploaded
if(!empty($this->request->data['Post']['Image']))
{
foreach ($this->request->data['Post']['Image'] as $i => $image)
{
$file = $this->request->data['Post']['Image'][$i];
$tmp = $file['tmp_name'];
// debug( $file);
// debug( $tmp );
// die();
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
//get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
$name = substr(md5(time()), 0,10).$i.'.'.$ext;
$path = $rootfolder.$name;
debug($name);
debug($path);
// die();
move_uploaded_file($tmp,$path);
$file = array('name'=>$file['name'],'path' => $path );
debug($file);
$images[] = $file;
// $this->data['Post']['image']['name'] = $file['name']
// $this->Post->data['Image']['image'];
// $this->data->Post['Image']['image'] = $file['name'];
}
}
debug($images);
// die();
//now do the save (optional)
} //if($this->Image->save($this->data)) {...} else {...}
}
$this->Post->create();
// the save() method will check for validation errors and abort the save if any occur
// pr ($this->request->data);
// die();
$this->request->data['Post']['user_id'] = AuthComponent::user('id');
if ($this->Post->saveAll($this->request->data)) {
$this->Flash->success(__('Your post has been saved.'));
// redirect function redirects to another URL
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('Unable to add your post.'));
}
$catagories = $this->Post->Catagory->find('list');
$this->set(compact('catagories'));
$image = $this->Post->Image->find('list');
$this->set(compact('image'));
}
有人可以帮我完成这些吗?谢谢。