php代码上传多个图片

时间:2016-08-11 08:53:12

标签: php cakephp cakephp-2.0

我有两个表格

产品和产品图表..

我想在产品图片表中插入多张图片。

下面的

是我的控制器代码...

代码正在运行,但它只在我的表中上传单个图像..

但我想上传多张图片..我很有趣的cakephp 2.x

请帮我解决这个问题......

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>

1 个答案:

答案 0 :(得分:0)

埃洛,伙计。 您可以将产品图像排列成数组,例如:

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

然后你调用方法 saveMany()而不是save()

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