如何在cakephp上传文件

时间:2014-06-26 07:25:31

标签: cakephp cakephp-2.0

我想使用cakephp上传图片,我可以在数据库中保存文件名,但我的文件文件没有在指​​定的路径上传,我尝试了下面的代码,但我的问题没有解决

这是我的控制器

function editprofile ($id = NULL){
                if(empty($this->data)){
                    $this->data=$this->Signup->read(NULL, $id);
                }
                else{
              $image = $this->data['Signup']['upload image'];
                //allowed image types
                $imageTypes = array("image/gif", "image/jpeg", "image/png");
                //upload folder - make sure to create one in webroot
                $uploadFolder = "upload";
                //full path to upload folder
                $uploadPath = WWW_ROOT . $uploadFolder;
 $imageName = $image['name'];
 if($image['size'] > 2097152){
            $errors[]='File size must be less than 2 MB';
        }   
                //check if image type fits one of allowed types
                if(empty($errors)==true){
            if(is_dir($uploadPath)==false){
                mkdir("$uploadPath", 0700);     // Create directory if it does not exist
            }
            if(is_dir("$uploadPath/".$imageName)==false){
                move_uploaded_file($image['tmp_name'],"$uploadPath/".$imageName);
            }else{                                  // rename the file if another one exist
                $new_dir="$uploadPath/".$imageName.time();
                 rename($image['tmp_name'],$new_dir) ;              
            }

        }

                    if ($this->Signup->save($this->data)) {
                        $this->Session->setFlash($imageName);
                        return $this->redirect(array('action' => 'editprofile',$id));
                    }


                }
                $this->set('languageOptions', array('opt1' => 'Choose Occupuation', 'opt2' => 'Student', 'opt3' => 'Employee'));
    debug($this->Signup->validationErrors);
    debug($this->Signup->getDataSource()->getLog(false, false));
                 //$this->set('title_for_layout', 'Add a post ');
        }

这是我的观点

echo $this->Form->input('upload image',array( 'type' => 'file' , 'style' => 'margin-left:9%;'));

1 个答案:

答案 0 :(得分:1)

我自己多次遇到过这个问题,而且大多数情况下问题都是由我一直忘记的细节引起的:为表单设置正确的enctype。根据您的上述代码,我无法看到任何明显的错误,但我无法查看enctype是否设置为multipart/form-data。在视图中创建表单时请尝试此操作(请注意'type' => 'file'):

echo $this->Form->create('FormName', array('type' => 'file'));