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

时间:2022-09-11 13:46:31

I am working on multiple image file uploads using cakephp 3, where, I want those images be uploaded in server as specified in directory path of my code and, each of the uploaded image should be save in database (am using MySQL Database).

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

On my current build, I can select multiple images in my form, fortunately, after submitting my form, all images are successfully uploaded to server image directory path as I expected, the thing is only one(1) image are saved in database, as it should saved all and each of the images in database.

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

Herewith a copy of code in my ImageUploadController:

这是我的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']);
}

And here is my simple form: add.ctp file: simple multiple image upload form

这是我的简单形式:add.ctp文件:简单的多图像上传表单

And here is my model table UploadImageTable:

这是我的模型表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;
    }
}

I am quite new CakePHP 3, so you all guys who knew something about this uploading multiple images and saving each images in a database, please give me a hand or something could help me out of this, coz' am kinda stucked in this thing. Any help from you will be much appreciated.

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

For more additional details, herewith added a screenshot of my debugger SQL Logs.In the image,I tried to upload 5 images

有关更多其他详细信息,请添加我的调试器SQL Logs的屏幕截图。在图像中,我尝试上传5个图像

if you can see the image, as I tried to upload 5 images; at first query it executes an INSERT to my table and then the next other queries are UPDATE, which should be INSERT. I am wondering why DML(Data Manipulation Language)suddenly change in such queries.

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

more thanks in advance, Mary

玛丽,提前谢谢

1 个解决方案

#1


0  

Since you want to save several Images you have to create also multiple Entities to save in your database. With your current Controller you're creating a single Entity and saving the data to this Entity.

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

In your UploadedImagesController try the following:

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

You can solve this problem also by saving multiple Entities directly. You may also want to outsource your code to a Model or a Behavior to make it reusable in other Controllers. Like burzum mentioned it could be wise to use a file storage plugin to add things like file hashing and/or unique Ids (eg. UUID). Otherwise you could upload files with the same name...

您也可以通过直接保存多个实体来解决此问题。您可能还希望将代码外包给模型或行为,以使其在其他控制器中可重用。像burzum提到的那样,使用文件存储插件来添加诸如文件散列和/或唯一ID(例如UUID)之类的东西是明智的。否则你可以上传同名文件......

#1


0  

Since you want to save several Images you have to create also multiple Entities to save in your database. With your current Controller you're creating a single Entity and saving the data to this Entity.

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

In your UploadedImagesController try the following:

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

You can solve this problem also by saving multiple Entities directly. You may also want to outsource your code to a Model or a Behavior to make it reusable in other Controllers. Like burzum mentioned it could be wise to use a file storage plugin to add things like file hashing and/or unique Ids (eg. UUID). Otherwise you could upload files with the same name...

您也可以通过直接保存多个实体来解决此问题。您可能还希望将代码外包给模型或行为,以使其在其他控制器中可重用。像burzum提到的那样,使用文件存储插件来添加诸如文件散列和/或唯一ID(例如UUID)之类的东西是明智的。否则你可以上传同名文件......