2016-08-11 122 views
0

我有兩個PHP代碼上傳多張圖片

產品和productimage表..

我想插入產品形象表中的多個圖像。

下面

是我的控制器代碼...

代碼工作,但它只是上傳單個圖像......在我的表...

但我要上傳多個images..i有趣CakePHP的2.x的

plz幫助我解決這個...

public function addProduct() { 

      if (is_uploaded_file($this->request->data['Product']['file']['tmp_name'])) { 
       $pathToUpload = "img/Frontend/Products/" . $this->Auth->User('Profile.user_id') . '/'; 
       $pathToUploadThumbnail = "img/Frontend/Products/" . $this->Auth->User('Profile.user_id') . "/Thumbnails/"; 
       if (!(is_dir($pathToUpload))) { 
        mkdir($pathToUpload, 0777); 
        mkdir($pathToUploadThumbnail, 0777); 
       } 
       $fileName = $this->request->data['Product']['file']['name']; 
       $ext = pathinfo($fileName, PATHINFO_EXTENSION); 
       $this->request->data['Product']['file_name'] = $this->request->data['Product']['title'] . time() . '.' . $ext; 
       $fileName = str_replace('/', 'A', $this->request->data['Product']['file_name']); 
       move_uploaded_file($this->request->data['Product']['file']['tmp_name'], $pathToUpload . $fileName); 
      }   

      if ($this->Product->save($productData)) { 
       $this->loadModel('ProductImage'); 
       if (!empty($this->request->data['Product']['file_name'])) { 
        $productImage['ProductImage']['product_id'] = $this->Product->getLastInsertID(); 
        $productImage['ProductImage']['image'] = $fileName; 
        $this->ProductImage->save($productImage); 
       } 

       $this->Session->setFlash('Product has been added.'); 
       $this->redirect('productListing'); 
      } 
     } 
} 
?> 

**photo upload button** 

<?php 
echo $this->Form->input('Product.file', array('type' => 'file','label'=>false,'div'=>false,'class'=>'input_bar')); 
?> 

我使用下面的腳本生成瀏覽按鈕

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#more').on('click', function(){ 
     var newfield = '<div class="keyword"><input type="file" class="input_bar" name="data[Product][file][]"><button class="add_more_img btn btn-lg btn-primary update remove">Remove</button></div>'; 
     $('#main').append(newfield); 
    }); 
    $(document).on('click','.remove', function(){ 
     $(this).parent('div').remove(); 
    }); 
}); 
</script> 
+0

檢查[這](HTTP:/ /stackoverflow.com/questions/37981807/cakephp-3-multiple-file-uploading-returns-string-instead-of-array/37983795#37983795) –

回答

0

你好,隊友。 你可以安排你的產品圖片到一個數組,例如像:

$data_to_save = array(
    array('data' => 'value', 'data' => 'value'), 
    array('data' => 'value', 'data' => 'value') 
); 

然後調用方法saveMany(),而不是保存()

$this->ProductImage->saveMany($data_to_save);