如何在CakePHP 3中:将多个图像上传到服务器并使用cakephp 3将每个图像保存在数据库中

时间:2017-09-15 07:54:42

标签: php mysql image cakephp file-upload

我正在使用cakephp 3处理多个图像文件上传,其中,我希望这些图像在我的代码的目录路径中指定的服务器上传,并且每个上传的图像都应该保存在数据库中(使用MySQL数据库) )。

在我目前的构建中,我可以在我的表单中选择多个图像,幸运的是,在提交表单后,所有图像都按照我的预期成功上传到服务器图像目录路径,事情只保存了一(1)个图像数据库,因为它应该保存数据库中的所有和每个图像。

这是我的ImageUploadController中的代码副本:

public function add()
{
    $UploadedImage = array();
    $uploadedImage = $this->UploadedImages->newEntity();

    if ($this->request->is('post')) {

        $images = array();

        $images = $this->request->data['name'];

        foreach ($images as $key => $image) {

          if(!empty($image[$key].$image['name'])){
            $fileName = $image[$key].$image['name'];
            $uploadPath = WWW_ROOT.'img/press-releases/';
            $uploadFile = $uploadPath.$fileName;


            if(move_uploaded_file($image[$key].$image['tmp_name'],$uploadFile)){

                $uploadedImage->name = $fileName;
                $uploadedImage->image_dir = 'press-releases/';
                $uploadedImage->status = $this->request->data['status'];

                $this->UploadedImages->save($uploadedImage);

            } else {  $this->Flash->error(__('Unable to upload image, please try again.'));  }


           } else { $this->Flash->error(__('Please choose an image to upload.')); } 

        }//EOF FOREACH      

    }

    $this->set(compact('uploadedImage'));
    $this->set('_serialize', ['uploadedImage']);
}

这是我的简单形式:add.ctp文件: simple multiple image upload form

这是我的模型表UploadImageTable:

class UploadedImagesTable extends Table
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('uploaded_images');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->allowEmpty('name');

        $validator
            ->allowEmpty('image_dir');

        $validator
            ->boolean('status')
            ->allowEmpty('status');

        return $validator;
    }
}

我是一个非常新的CakePHP 3,所以你们都知道这个上传多个图像并将每个图像保存在数据库中的所有人,请给我一个手或者什么东西可以帮助我摆脱这个,因为我有点被困在这件事上。非常感谢您提供的任何帮助。

有关更多其他详细信息,请添加我的调试程序SQL日志的屏幕截图。In the image,I tried to upload 5 images

如果你能看到图像,我试图上传5张图片;在第一次查询它执行INSERT到我的表然后接下来的其他查询是UPDATE,应该是INSERT。我想知道为什么DML(数据操作语言)在这样的查询中突然发生变化。

提前多谢, 玛丽

1 个答案:

答案 0 :(得分:0)

由于您要保存多个图像,因此您还必须创建多个实体以保存在数据库中。使用您当前的控制器,您可以创建单个实体并将数据保存到此实体。

在UploadedImagesController中尝试以下操作:

public function add()
{
    if ($this->request->is('post')) {
        $data = $this->request->getData();

        $images = $data['name'];
        $path = 'img/press-releases/';

        foreach ($images as $image) {
            if(!empty($image['name'])) {
                $fileName = $image['name'];
                $uploadPath = WWW_ROOT . $path;
                $uploadFile = $uploadPath . $fileName;

                if(move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    // Create a new Entity over here for each uploaded image
                    $uploadedImage = $this->UploadedImages->newEntity();
                    $uploadedImage->name = $fileName;
                    $uploadedImage->image_dir = $path;
                    $uploadedImage->status = $data['status'];

                    $this->UploadedImages->save($uploadedImage)
                } else {
                    $this->Flash->error(__('Unable to upload image, please try again.'));
                }
            } else {
                $this->Flash->error(__('Please choose an image to upload.'));
            }
        }
    }

    $this->set(compact('uploadedImage'));
    $this->set('_serialize', ['uploadedImage']);
}

您也可以直接通过saving multiple Entities解决此问题。您可能还希望将代码外包给模型或Behavior,以使其可在其他控制器中重复使用。像burzum提到的那样,使用file storage plugin添加文件散列和/或唯一ID(例如UUID)之类的东西是明智的。否则你可以上传同名文件......