Reputation: 45
I am able to upload a single image in CakePHP but I want upload multiple images at once. How can I achieve it?
My Controller page is like this:
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');
}
My view page is like this
<?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>
Upvotes: 1
Views: 4459
Reputation: 6047
It's possible by adding 2 or more input fields in your form like this:
for($i=0;$i<10;$i++){
echo $this->Form->input('image.', array('type' => 'file')); //note the . at the end of the name.
}
This way the name of the file will be: data[Image][image][] and if you print the data in your controller, you will see the array of images.
The other way is by using ajax upload library such as: fineuploader.com
Upvotes: 1