Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload multiple files with Zend framework?

Even if I select 2 or more images, only one gets uploaded.

I have a simple form:

<form action="/images/thumbs" method="post" enctype="multipart/form-data">
    <input name="file[]" id="file" type="file" multiple="" />
    <input type="submit" name="upload_images" value="Upload Images">
</form>

Then in my controller:

public function thumbsAction()
{
    $request = $this->getRequest();

    if ($request->isPost()) {
        if (isset($_POST['upload_images'])) {
            $names = $_FILES['file']['name'];

            // the names will be an array of names
            foreach($names as $name){
                $path = APPLICATION_PATH.'/../public/img/'.$name;
                echo $path; // will return all the paths of all the images that i selected
                $uploaded = Application_Model_Functions::upload($path);
                echo $uploaded; // will return true as many times as i select pictures, though only one file gets uploaded
            }
        }
    }
}

and the upload method:

public static function upload($path)
{
    $upload = new Zend_File_Transfer_Adapter_Http();
    $upload->addFilter('Rename', array(
        'target'    => $path,
        'overwrite' => true
    ));

    try {
        $upload->receive();
        return true;
    } catch (Zend_File_Transfer_Exception $e) {
        echo $e->message();
    }
}

Any ideas why I get only one file uploaded?

like image 561
Patrioticcow Avatar asked Apr 28 '13 21:04

Patrioticcow


1 Answers

Zend_File_Transfer_Adapter_Http actually has the information about the file upload. You just have to iterate using that resource:

$upload = new Zend_File_Transfer_Adapter_Http();
$files  = $upload->getFileInfo();
foreach($files as $file => $fileInfo) {
    if ($upload->isUploaded($file)) {
        if ($upload->isValid($file)) {
            if ($upload->receive($file)) {
                $info = $upload->getFileInfo($file);
                $tmp  = $info[$file]['tmp_name'];
                // here $tmp is the location of the uploaded file on the server
                // var_dump($info); to see all the fields you can use
            }
         }
     }
}
like image 161
Dinesh Avatar answered Nov 03 '22 02:11

Dinesh