Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

php - cakePHP 3.0 uploading images

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]

Are there already some examples for uploading files (multiple files at once) in cakePHP 3.0? Because I can only find examples for cakePHP 2.x !

I think I need to add a custom validation method in my ImagesTable.php? But I can't get it to work.

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']);
    }

Image add.ctp

<?php
   echo $this->Form->input('image_path', [
      'label' => 'Image',
      'type' => 'file'
      ]
   );
?>

Image Entity

protected $_accessible = [
    'image_path' => true,
];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

<div class="ChImg">
<?php 
echo $this->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();       
?>
</div>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...