2014-02-08 23 views
1

我可以在CakePHP中上傳單個圖像,但我想一次上傳多個圖像。我怎樣才能實現它?如何在CakePHP中上傳多個圖像

我控制器頁是這樣的:

public function display() { 
    if ($this->request->is('post')) { 
      if ($this->data['Image']) { 
       $image = $this->data['Image']['image']; 
       //allowed image types 
       $imageTypes = array("image/gif", "image/jpeg", "image/png"); 
       //upload folder - make sure to create one in webroot 
       $uploadFolder = "upload"; 
       //full path to upload folder 
       $uploadPath = WWW_ROOT . $uploadFolder; 


       //check if image type fits one of allowed types 
       foreach ($imageTypes as $type) { 
        if ($type == $image['type']) { 
         //check if there wasn't errors uploading file on serwer 
         if ($image['error'] == 0) { 
          //image file name 
          $imageName = $image['name']; 
          //check if file exists in upload folder 
          if (file_exists($uploadPath . '/' . $imageName)) { 
              //create full filename with timestamp 
           $imageName = date('His') . $imageName; 
          } 
          //create full path with image name 
          $full_image_path = $uploadPath . '/' . $imageName; 
          //upload image to upload folder 
          if (move_uploaded_file($image['tmp_name'], $full_image_path)) { 
           $this->Session->setFlash('File saved successfully'); 
           $this->set('imageName',$imageName); 
          } else { 
           $this->Session->setFlash('There was a problem uploading file. Please try again.'); 
          } 
         } else { 
          $this->Session->setFlash('Error uploading file.'); 
         } 
         break; 
        } else { 
         $this->Session->setFlash('Unacceptable file type'); 
        } 
       } 
      } 
     } 
     $this->render('home'); 
    } 

我的看法頁面是這樣的

<?php 
/* display message saved in session if any */ 
echo $this->Session->flash(); 
?> 
<div> 
<div class="images-form"> 
<?php echo $this->Form->create('Image', array('type' => 'file')); ?> 
    <fieldset> 
     <legend><?php echo __('Add Image'); ?></legend> 
     <?php 

     echo $this->Form->input('image', array('type' => 'file')); 
    ?> 
    </fieldset> 
<?php echo $this->Form->end(__('Submit')); ?> 

</div> 
<div class="image-display"> 
<?php 

//if is set imageName show uploaded picture 

if(isset($imageName)) { 
echo $this->Html->image('/upload/'.$imageName, array('alt' => 'uploaded image')); 
} 
?> 
</div> 
</div> 

回答

1

有可能通過增加2個或多個輸入字段的表單是這樣的:

for($i=0;$i<10;$i++){ 
    echo $this->Form->input('image.', array('type' => 'file')); //note the . at the end of the name. 
} 

這樣,文件的名稱將是:data [Image] [image] [],如果您在控制器中打印數據,你會看到圖像陣列。

另一種方式是通過使用ajax上傳庫如:fineuploader.com

+0

我正在使用這個,但它只是拋出一個錯誤。 .dot應該做什麼? – Isengo