我只想在我的函数中添加(添加)我的蛋糕应用程序中的文件上传过程。我已尝试过各种各样的教程,我可以找到我的问题的解决方案。我是新手蛋糕,我不想重新发明我想根据迄今为止实施的内容学习的轮子。我非常感谢你的帮助。
add.ctp
<?php echo $this->Form->create('Movie'); ?>
<?php echo __('Add Movie'); ?>
<?php
echo $this->Form->hidden('movie_id');
echo $this->Form->input('title');
echo $this->Form->input('date', array(
'type' => 'date',
'label' => 'Date',
'empty' => false,
'dateFormat' => 'DMY',
'minYear'=>'1990',
'maxYear'=>date('Y'),
));
echo $this->Form->input('description');
echo $this->Form->input('file', array('type' => 'file'));?>
<?php echo $this->Form->end(__('Submit')); ?>
控制器
public function add() {
if ($this->request->is('post')) {
$this->Movie->create();
}
if ($this->Movie->save($this->request->data))
{
$this->Session->setFlash(__('The movie has been created'));
$this->redirect (array('action'=>'index'));
}
}
答案 0 :(得分:0)
表movies
的表结构
CREATE TABLE IF NOT EXISTS `movies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`movie_id` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
`file` varchar(200) NOT NULL,
`date` date NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `movie_id` (`movie_id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
创建位于/app/Model/Movies.php的模型
<?php
class Movie extends AppModel {
}
?>
在app / Controller / Movies.php中创建控制器
<?php
class MoviesController extends AppController {
public function add() {
if ($this->request->is('post')) {
$maxId = $this->Movie->find('first', array(
'order' => 'movie_id DESC',
'fields' => array('Movie.movie_id')
));
$maxId = (isset($maxId['Movie']['movie_id'])? $maxId['Movie']['movie_id'] : 0);
$this->request->data['Movie']['movie_id'] = $maxId+1;
$folderToSaveFiles = WWW_ROOT . 'img/uploads/' ;
if(!empty($this->request->data['Movie']['file']))
{
$file = $this->request->data['Movie']['file'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
$arr_ext = array('jpg', 'jpeg', 'gif','png');
if(in_array($ext, $arr_ext))
{
$newFilename = $this->request->data['Movie']['title'].'.'.$ext;
$result = move_uploaded_file( $file['tmp_name'], $folderToSaveFiles . $newFilename );
$this->request->data['Movie']['file'] = $newFilename;
$this->Movie->save($this->request->data);
//debug($this->request->data);
}
}
}
}
注意:在app / webroot / img / uploads /&amp;中创建一个目录上传目录必须是写权限。