【问题标题】:How to upload multiple images and save it in server using cakephp 3.3如何使用 cakephp 3.3 上传多个图像并将其保存在服务器中
【发布时间】:2016-12-03 20:54:52
【问题描述】:

我正在使用 cakephp 3.3。我可以上传单个图像,但它没有保存在 webroot/uploads 下。我想上传多张图片并保存。我怎样才能实现它?请提供一些输入。我对 PHP 编程和这个框架非常陌生。谢谢!

       `Images\add.ctp
       <?= $this->Form->create($image,['type' => 'file']) ?>
       <fieldset>
       <legend><?= __('Add Image') ?></legend>
       <?php

       echo $this->Form->input('path',['type' => 'file']);
       ?>
       </fieldset>`

        ImagesController\add

        public function add()
{
    $image = $this->Images->newEntity();
    if ($this->request->is('post')) {
        $image = $this->Images->patchEntity($image, $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.'));
        }
    }
    $properties = $this->Images->Properties->find('list', ['limit' => 200]);
    $this->set(compact('image', 'properties'));
    $this->set('_serialize', ['image']);
}

          Table\ImageTable.php

      $validator
        ->requirePresence('path', 'create')
        ->notEmpty('path')
    ->add('processImageUpload', 'custom', [
      'rule' => 'processImageUpload'
   ]);

 public function processImageUpload($check = array()) {
if(!is_uploaded_file($check['path']['tmp_name'])){
   return FALSE;
}
if (!move_uploaded_file($check['path']['tmp_name'], WWW_ROOT . 'img' . DS .   'images' . DS . $check['path']['name'])){
    return FALSE;
}
$this->data[$this->alias]['path'] = 'images' . DS . $check['path']['name'];
return TRUE;

}

【问题讨论】:

  • 到目前为止你尝试了什么??同时发布您的进度。
  • 我在 add.ctp 中创建了输入类型文件,然后使用 move_uploded_file() 方法处理上传。我已经添加了上面的代码。谢谢!

标签: cakephp cakephp-3.3


【解决方案1】:

在 add.ctp 中使输入字​​段类似于:

echo $this->Form->input('path[]',['type' => 'file','multiple'=>'multiple']);

并且在控制器中制作保存方法是这样的:

// $image = $this->Images->newEntity();
$images= $this->Articles->newEntities($this->request->data);
if ($this->request->is('post')) {
    // $image = $this->Images->patchEntity($image, $this->request->data);
    if ($this->Images->saveMany($images)) {
        $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”以获取每个图像详细信息并存储在数据库中。并将图像保存在 Webroot\uploads 下。 $images= $this->Images->newEntities($this->request->data);会给我一系列图像。但是我在尝试获取文件名时找不到索引。
  • @Manohar Khadka:我试过这种方式!那没起效。它让我无法找到表类条目作为错误。
猜你喜欢
  • 2018-02-24
  • 1970-01-01
  • 2011-08-15
  • 2012-11-17
  • 2011-09-19
  • 2015-12-30
  • 2012-04-07
  • 1970-01-01
  • 2010-12-09
相关资源
最近更新 更多