我可以在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>
答案 0 :(得分: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