Multiple File Upload in Cakephp 2.x
Hello friends welcome to findnerd. In this blog we are going to learn how to post multiple images at a time in cakephp. Lets create the table posts for saving images
CREATE TABLE `posts` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(200) NOT NULL,
`body` text NOT NULL,
`image1` varchar(200),
`image2` varchar(200),
`image3` varchar(200),
PRIMARY KEY (`id`)
)
Now you can see that there are 3 fields for uploading images image1, image2 and image3 in the posts table. Now add the code given below for uploading multiple images. Here uploaded images will be stored in app/webroot/uploads/posts
folder. If in case of NULL values or if the image is not correct then I have one default image available called 'noimage-available.jpg
'.
public function add() {
$this->Post->create();
if ($this->request->is('post')) {
// Image Handling code START //////
for($i=1;$i<4;$i++)
{
if(empty($this->data['Post']['image'.$i]['name'])){
unset($this->request->data['Post']['image'.$i]);
}
if(!empty($this->data['Post']['image'.$i]['name']))
{
$file=$this->data['Post']['image'.$i];
$ary_ext=array('jpg','jpeg','gif','png'); //array of allowed extensions
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . time().$file['name']);
$this->request->data['Post']['image'.$i] = time().$file['name'];
}
}
}
// Image Handling code END //////
if ($this->Post->save($this->request->data))
{
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('Unable to add your post.');
}
}
}
Edit function given below:
public function edit($id=null){
if(!$id)
{
throw new NotFoundException(__('Invalid Post'));
}
$post=$this->Post->findById($id);
if(!$post)
{
throw new NotFoundException(__('Invalid Post'));
}
if(!empty($this->data))
{
$this->Post->id=$id;
// Image Handling code START //////
for($i=1;$i<4;$i++)
{
if(empty($this->data['Post']['image'.$i]['name'])){
unset($this->request->data['Post']['image'.$i]);
}
if(!empty($this->data['Post']['image'.$i]['name']))
{
if(file_exists("img/uploads/posts/".$this->data['Post']['hiddenimage'.$i])){
unlink("img/uploads/posts/".$this->data['Post']['hiddenimage'.$i]);
}
$file=$this->data['Post']['image'.$i];
$ary_ext=array('jpg','jpeg','gif','png'); //array of allowed extensions
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . time().$file['name']);
$this->request->data['Post']['image'.$i] = time().$file['name'];
}
}
}
// Image Handling code END //////
if($this->Post->save($this->request->data))
{
$this->Session->setFlash('Your Post has been Updated');
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash('Unable to update your post.');
}
}
if(!$this->request->data){
$this->request->data=$post;
}
}
In order to get html similar to the following you need to use the cake input helper.
<input name='uploads[]' type=file multiple>
To achieve this html we need to use the Form helper. Write the following code in ctp file:
<?php
echo $this->Form->create('User', array('type' => 'file'));
echo $this->Form->input('files.', array('type' => 'file', 'multiple'));
echo $this->Form->end('Submit');
?>
Now on controller, you can get the file data by using $this->data or $this->request->data. You can see the following output by submitting the form:
Array
(
[User] => Array
(
[files] => Array
(
[0] => Array
(
[name] => amuk.jpg
[type] => image/jpeg
[tmp_name] => D:\MyPictures\tmp\php444.tmp
[error] => 0
[size] => 1526742
)
[1] => Array
(
[name] => hello.jpg
[type] => image/jpeg
[tmp_name] => D:\MyPictures\tmp\php112.tmp
[error] => 0
[size] => 2233068
)
)
)
Looping through the files array and process them.
Another way of developing the View files for add and edit is given below:
add.ctp
<!-- File: /app/View/Posts/add.ctp -->
<h1>Add Post</h1><?php
echo $this->Form->create('Post', array('url' => array('action' => 'add'), 'enctype' => 'multipart/form-data'));
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
for($i=1; $i<4; $i++)
{
?>
<div id="attachment<?php echo $i;?>" <?php if($i !=1) echo "style='display:none;'";?> >
<div>
<?php echo $this->Form->input('image'.$i,array('type'=>'file','label' => false,'div' => false));?>
</div>
<div id="attachmentlink<?php echo $i;?>" <?php if($i==3) echo "style='display:none;'";?>><a href="javascript:void(0);" onclick="show('attachment<?php echo $i+1;?>'); hide('attachmentlink<?php echo $i;?>');">Add Another Attachment</a></div>
</div>
<?php } ?>
<?php
echo $this->Form->end('Save Post');
?>
<script>
function show(target){
document.getElementById(target).style.display = 'block';
}
function hide(target){
document.getElementById(target).style.display = 'none';
}
</script>
edit.ctp
<!-- File: /app/View/Posts/edit.ctp -->
<h1>Edit Post
</h1><?php
echo $this->Form->create('Post', array('url' => array('action' => 'edit'), 'enctype' => 'multipart/form-data'));
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
for($i=1; $i<4; $i++)
{
?>
<div>
<?php
$ProductImage = $this->Form->value('image'.$i);
if(empty($ProductImage) || $ProductImage==NULL)
{
$ProductImage = "/img/uploads/posts/noimage-available.jpg";
}
else
{
$ProductImage = "/img/uploads/posts/".$ProductImage;
}
echo $this->Form->input('image'.$i,array('type'=>'file','label' => false,'div' => false));
echo $this->Form->input('hiddenimage'.$i,array('type'=>'hidden','value'=>$this->Form->value('image'.$i)));
echo $this->Html->image($ProductImage,array('align'=>'absbottom','style'=>'max-height:100px'));
?>
</div>
<?php }
echo $this->Form->end('Save Post');
?>
Posts listing for images: index.ctp
<!-- File: /app/View/Posts/index.ctp -->
<?php echo $this->Html->link('Add',array('action'=>'add'));?><br/><br/>
<table width="100%" id="tbl">
<tr>
<th><?php echo 'id'; ?></th>
<th><?php echo 'title'; ?></th>
<th><?php echo 'Body'; ?></th>
<th><?php echo 'Image1'; ?></th>
<th><?php echo 'Image2'; ?></th>
<th><?php echo 'Image3'; ?></th>
<th><?php echo 'Actions'; ?></th>
</tr>
<?php foreach ($posts as $post):?>
<tr>
<td style="width:10%"><?php echo $post['Post']['id'];?></td>
<td style="width:15%"><?php echo $post['Post']['title'];?><br/></td>
<td style="width:20%"><?php echo $post['Post']['body']?></td>
<td style="width:10%"><?php //echo $this->Html->image('/img/uploads/posts/'.$post['Post']['image1'],array('style'=>'max-height:100px'));?>
<?php
$MyImage = $post['Post']['image1'];
if (file_exists("img/uploads/posts/".$MyImage))
$MyImage1 ="/img/uploads/posts/".$MyImage;
else
$MyImage1 = "/img/uploads/posts/noimage-available.jpg";
if($MyImage=='NULL' || $MyImage=='')
$MyImage1 = "/img/uploads/posts/noimage-available.jpg";
echo $this->Html->image($MyImage1);
?></td>
<td style="width:10%"><?php //echo $this->Html->image('/img/uploads/posts/'.$post['Post']['image2'],array('style'=>'max-height:100px'));?>
<?php
$MyImage = $post['Post']['image2'];
if (file_exists("img/uploads/posts/".$MyImage))
$MyImage2 ="/img/uploads/posts/".$MyImage;
else
$MyImage2 = "/img/uploads/posts/noimage-available.jpg";
if($MyImage=='NULL' || $MyImage=='')
$MyImage2 = "/img/uploads/posts/noimage-available.jpg";
echo $this->Html->image($MyImage2);
?></td>
<td style="width:10%"><?php //echo $this->Html->image('/img/uploads/posts/'.$post['Post']['image3'],array('style'=>'max-height:100px'));?>
<?php
$MyImage = $post['Post']['image3'];
if (file_exists("img/uploads/posts/".$MyImage))
$MyImage3 ="/img/uploads/posts/".$MyImage;
else
$MyImage3 = "/img/uploads/posts/noimage-available.jpg";
if($MyImage=='NULL' || $MyImage=='')
$MyImage3 = "/img/uploads/posts/noimage-available.jpg";
echo $this->Html->image($MyImage3);
?></td>
<td>
<?php echo $this->Html->link('View',array('action'=>'view',$post['Post']['id']));?>
<?php echo $this->Html->link('Edit',array('action'=>'edit',$post['Post']['id']));?>
<?php echo $this->Form->postLink('Delete',array('action'=>'delete',$post['Post']['id']),array('confirm'=>'Are You sure..??'));?></td>
</tr>
<?php endforeach;?>
<?php unset($post);?>
</table>
Code for view.ctp file:
<!-- File: /app/View/Posts/view.ctp -->
<h1>ID : <?php echo h($post['Post']['id']); ?></h1>
<h1>TItle : <?php echo h($post['Post']['title']); ?></h1>
<h1>Body : <?php echo h($post['Post']['body']); ?></h1>
<?php
for($i=1;$i<4;$i++)
{
if(!empty($post['Post']['image'.$i]))
{
echo $this->Html->image('/img/uploads/posts/'.$post['Post']['image'.$i]); ?>
<?php }
}?>
Thanks for reading.
0 Comment(s)