2017-09-14 60 views
0

嗨,有人可以知道我是初學CakePHP我試圖上傳多個圖像,但它不會保存。數組保存cakephp 3 savemany

控制器:

public function add() { 
if ($this->request->is('post')) { 
    //$data = $this->request->getData(); 
    if(!empty($_FILES['photo']['name'])){ 
     $count = count($_FILES['photo']['name']); 
     for ($i=0; $i < $count; $i++) { 
      $filename = $_FILES['photo']['name'][$i]; 
      $type = $_FILES['photo']['type'][$i]; 
      $tmp = $_FILES['photo']['tmp_name'][$i]; 
      $error = $_FILES['photo']['error'][$i]; 
      $size = $_FILES['photo']['size'][$i]; 
      $uploadPath = '../uploads/files/'; 

      $file[$i]['user_id'] = $this->Auth->user('id'); 
      $file[$i]['filename'] = $filename; 
      $file[$i]['file_location'] = $uploadPath; 
      $file[$i]['file_type'] = $type; 
      $file[$i]['file_size'] = $size; 
      $file[$i]['file_status'] = 'Active'; 
      $file[$i]['created'] = date("Y-m-d H:i:s"); 
      $file[$i]['modified'] = date("Y-m-d H:i:s"); 
     } 
     $table = TableRegistry::get('files'); 
     $entities = $table->newEntities($file); 
     if($table->saveMany($entities)) { 
      $this->Flash->success(__('File has been uploaded and inserted successfully.')); 
      return $this->redirect(['action' => 'index']); 
     } else { 
      $this->Flash->error(__('Unable to upload file, please try again.')); 
     } 

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

} 但是當我試圖調試都不錯,但在拯救它不會工作!沒有我的代碼有問題,誰能幫我如何解決我的附加功能

查看:

echo $this->Form->input('photo[]', ['type' => 'file','multiple' => 'true','label' => 'Upload Multiple Photos']); 

回答

0

您試圖保存一次使用saveMany一個記錄()。

public function add() 
{ 
    if ($this->request->is('post')) { 
     $table = TableRegistry::get('files'); 
     $uploadPath = '../uploads/files/'; 

     if(!empty($_FILES['photo'])){ 
      foreach ($_FILES['photo'] as $EachPhoto) { 
       $data[] = [ 
        'user_id' => $this->Auth->user('id'), 
        'filename' => $EachPhoto['name'], 
        'file_location' => $uploadPath, 
        'file_type' => $EachPhoto['type'], 
        'file_size' => $EachPhoto['size'], 
        'file_status' => 'Active', 
        'created' => date("Y-m-d H:i:s") 
       ]; 
      } 

      $entities = $table->newEntities($data); 
      if($this->Files->saveMany($entitie)) { 
        $this->Flash->success(__('File has been uploaded and inserted successfully.')); 
        return $this->redirect(['action' => 'index']); 
      } else { 
        $this->Flash->error(__('Unable to upload file, please try again.')); 
      } 

     } else { 
      $this->Flash->error(__('Please choose a file to upload.')); 
     } 
    } 
} 
+0

我重建我的代碼,但結果相同,它不會保存在數據庫中,它會給出錯誤。 –

+0

這裏發佈什麼$ _FILES和$ this-> request-> data();正在打印。 –

+0

我已經編輯了我的代碼在頂部,$ _FILES是超級全局變量來獲取文件 –