cakePHP 3.0 uploading images

前端 未结 6 1302
北荒
北荒 2020-12-16 20:07

I want to upload images in my cakephp 3.0 app. But I get the error message:

Notice (8): Undefined index: Images [APP/Controller/ImagesController.php, line 55         


        
6条回答
  •  离开以前
    2020-12-16 20:39

    In your view file, add like this, in my case Users/dashboard.ctp

    Form->create($particularRecord, ['enctype' => 'multipart/form-data']); echo $this->Form->input('upload', ['type' => 'file']); echo $this->Form->button('Update Details', ['class' => 'btn btn-lg btn-success1 btn-block padding-t-b-15']); echo $this->Form->end(); ?>

    In your controller add like this, In my case UsersController

    if (!empty($this->request->data)) {
    if (!empty($this->request->data['upload']['name'])) {
    $file = $this->request->data['upload']; //put the data into a var for easy use
    
    $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
    $setNewFileName = time() . "_" . rand(000000, 999999);
    
    //only process if the extension is valid
    if (in_array($ext, $arr_ext)) {
        //do the actual uploading of the file. First arg is the tmp name, second arg is 
        //where we are putting it
        move_uploaded_file($file['tmp_name'], WWW_ROOT . '/upload/avatar/' . $setNewFileName . '.' . $ext);
    
        //prepare the filename for database entry 
        $imageFileName = $setNewFileName . '.' . $ext;
        }
    }
    
    $getFormvalue = $this->Users->patchEntity($particularRecord, $this->request->data);
    
    if (!empty($this->request->data['upload']['name'])) {
                $getFormvalue->avatar = $imageFileName;
    }
    
    
    if ($this->Users->save($getFormvalue)) {
       $this->Flash->success('Your profile has been sucessfully updated.');
       return $this->redirect(['controller' => 'Users', 'action' => 'dashboard']);
       } else {
       $this->Flash->error('Records not be saved. Please, try again.');
       }
    }
    

    Before using this, create a folder in webroot named upload/avatar.

    Note: The input('Name Here'), is used in

    $this->request->data['upload']['name']
    

    you can print it if you want to see the array result.

    Its works like a charm in CakePHP 3.x

提交回复
热议问题