2013-04-28 95 views
6

即使我选择了2张或更多张图片,也只能上传一张图片。如何使用Zend框架上传多个文件?

我有一个简单的表格:

<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> 
在我的控制器

然后:

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 
      } 
     } 
    } 
} 

upload方法:

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(); 
    } 
} 

任何想法,为什么我得到的只有一个文件上传?

回答

9

Zend_File_Transfer_Adapter_Http实际上有关于文件上传的信息。你只需要使用该资源迭代:

$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 
      } 
     } 
    } 
} 
+1

我觉得你的代码在这里有问题。 '$ apt'没有定义。你是不是指'$ upload'? – 2014-01-06 22:40:32

+0

更改..对不起.. – Dinesh 2014-07-04 23:08:46

+0

谢谢,这对我Zf2的伎俩。 – 2016-03-29 15:19:28