CakePHP多文件上传字段只上传一张图片

时间:2012-03-09 16:22:00

标签: php cakephp file-upload cakephp-2.0

我正在尝试使用多个上传文件字段上传一些文件。 POST信息正确发送,如下所示:

Array
(
    [Uploads] => Array
        (
            [photos] => Array
                (
                    [0] => Array
                        (
                            [name] => image - Copy - Copy.jpg
                            [type] => image/jpeg
                            [tmp_name] => /tmp/phpALAMwT
                            [error] => 0
                            [size] => 60892
                        )

                    [1] => Array
                        (
                            [name] => image - Copy.jpg
                            [type] => image/jpeg
                            [tmp_name] => /tmp/phpoIGtta
                            [error] => 0
                            [size] => 60892
                        )

                    [2] => Array
                        (
                            [name] => image.jpg
                            [type] => image/jpeg
                            [tmp_name] => /tmp/phpERTogu
                            [error] => 0
                            [size] => 60892
                        )

                )

我循环并将每个插入到数据库中,然后使用数据库中的ID上传它们,如下所示:

// Upload Photos
if (!empty($this->request->data['Uploads']['photos'][0]['tmp_name'])){

    foreach($this->request->data['Uploads']['photos']as $photo){

        $property_id = $this->request->data['Property']['ID'];
        $file_name = $photo['name'];
        $file_size = $photo['size'];
        $file_ext = pathinfo($photo['name'], PATHINFO_EXTENSION);

        // Save to DB
        $this->Property->PropertyImage->save(array(
            'PropertyImage' => array("Live"=>1, 'Number'=>99, "Type"=>'L', "FileType"=>$file_ext, "PropertyID"=>$property_id, 'Source'=>$file_name, 'Size=>'.$file_size)
        ));

        // Upload
        $id = $this->Property->PropertyImage->getLastInsertID();
        $path = intval($id/1000) . '/' . $id . '.' . $file_ext;
        move_uploaded_file($photo['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/imgp/F/'.$path);

    }
}

但是每次只有一个图像被放入数据库并上传,无法找出看起来不正常的原因。

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:2)

在行前你调用save()

$this->Property->PropertyImage->save(...)

呼叫

$this->Property->PropertyImage->create();

告诉模型写一个新记录,而不是继续使用刚刚保存的记录。