cakePHP 3.0 上传图片

2021-12-21 00:00:00 file-upload php cakephp

我想在我的 cakephp 3.0 应用程序中上传图片.但我收到错误消息:

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]

是否已经有一些在 cakePHP 3.0 中上传文件(一次多个文件)的示例?因为我只能找到 cakePHP 2.x 的示例!

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 !

我想我需要在我的 ImagesTable.php 中添加一个自定义验证方法?但我无法让它工作.

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

图像表

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;
}

图像控制器

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

图片添加.ctp

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

图像实体

protected $_accessible = [
    'image_path' => true,
];

推荐答案

也许以下内容会有所帮助.这是一种可以帮助您轻松上传文件的行为!

Maybe the following would help. It's a behavior who helps you to upload files very easy!

http://cakemanager.org/docs/utils/1.0/behaviors/可上传/

如果您遇到困难,请告诉我.

Let me know if you struggle.

问候

相关文章