无法在蛋糕PHP中上传多个图像

时间:2019-01-13 19:49:48

标签: cakephp cakephp-3.0

我正在创建一个表单,并尝试上传多个图像。单个图像就可以了。当我尝试上传多张图片时,然后我在输出中仅收到一张图片。 这是我的查看文件。

<div class="from-control-div">
 <?php echo $this->Form->create('Post', array('type' => 'file','id'=>'unitform','class'=>'form-horizontal','role'=>'form','url' => array('controller' => 'posts', 'action' => 'savepost')));?>
<div class="from-div-bottom">
    <div class="form-group">
        <label class="col-sm-4 control-label">File Upload</label>
        <div class="col-sm-6" id="more-files">
   <?php echo $this->Form->input('files.',array('type'=>'file','label' => false,'placeholder' => 'Upload images','id'=>"inputFile",'multiple','onchange'=>'readURL(this)'));?>
            <!--<div id="fileList"></div>-->
        </div>
        <a class="col-sm-2 pull-right" style="font-weight:bold;" id="add-more"><i class="fa fa-plus"></i> Add More</a>
    </div>
</div>  
  </form>

在这之后是我的控制器。如果我打印print_r($ data);然后输出是单个数组。没有收到多个数组。对我有帮助

Array ( [0] => Array ( [name] => download.jpg [type] => image/jpeg [tmp_name] => /tmp/phpX3Oy32 [error] => 0 [size] => 12988 ) )



      public function savepost() {
        if (count($this->request->data) > 0) {
      $fileNames = '';
            if (isset($this->request->data['Post']['files']) && count($this->request->data['Post']['files']) > 0) {
              $data=$this->request->data['Post']['files'];
                print_r($data);
             $fileNames = array();
                foreach ($this->request->data['Post']['files'] as $filedata) {
          if(isset($filedata["name"]) && ($filedata["name"] !='')){
            $upload_dir = FILE_UPLOAD_PATH;
            $original = explode('.', $filedata["name"]);
            $extension = array_pop($original);
            $newname = time() . '.' . $extension;
            if (file_exists($upload_dir . $newname)) {
              unlink($upload_dir . $newname);
            }
            if (move_uploaded_file($filedata["tmp_name"], $upload_dir . $newname)) {
              $fileNames[] = $newname;
                        print_r($fileNames);
            }
          }
                }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

公共功能savepost(){

if(isset($this->request->data['multifiles'])){
    $file_name_all="";
    for($i=0; $i<count($this->request->data['multifiles']); $i++){
        if(!empty($this->request->data['multifiles'][$i]['name'])){
            $file = $this->request->data['multifiles'][$i];
            $file['name'] =  time() . '-' . str_replace(' ', '_', $file['name']); 
            $uploadPath = WWW_ROOT . 'img/ ';
            $fileName =  $file['name'];
            $uploadFile = $uploadPath.$fileName;
            $file_name_all.= $file['name'].",";
            if($file['name']){
                move_uploaded_file($file['tmp_name'], $uploadFile);
            }  
        }
    }
}

}

在我的代码中,它正在工作。