本文简要介绍ZF2的文件上传。
首先我们来做一个最简单的文件上传:
Step:1
建立一个新模块Upload
目录结构如下:
/module /Upload /config module.cong.php /src /Upload /Controller IndexController.php /view /upload /index index.phtml Module.php
关于module.cong.php、 Module.php文件以及application.cong.php的配置这里就不多说了,详情见以前的文章。
Step 2:
index.phtml文件<>
<form method="POST" enctype="multipart/form-data"> <input type="file" name="fileupload" /"> <input type="submit" value="提交" /"> </form >
Step 3:
IndexController.php文件
<?php /** * 图片服务器视图助手 * * @author Star <wmistar@gmail.com> * @license http://mushroot.com * @version: 1.0 */ namespace Upload\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; use Zend\File\Transfer\Adapter\Http; class IndexController extends AbstractActionController { public function indexAction() { if ($this->getRequest()->isPost()) { $files = $this->getRequest()->getFiles(); $file = $files->fileupload; $fileAdapter = new Http(); //重新生成文件名 $newName = $this->oldName($file['name']); //储存文件 $fileAdapter->addFilter('File\Rename', array('target' => '/var/www/html/zftest/public/img/'.$newName, 'overwrite' => true, 'source' => $file['tmp_name'], )); if ($fileAdapter->receive($file['name'])) $resFile = $fileAdapter->getFilter('File\Rename')->getFile(); print_r($resFile); exit(); } return new ViewModel(); } public function oldName($oldName) { $oldType = substr($oldName,strrpos($oldName,".")); $this->type = $oldType; $newName = time().floor(microtime() * 10000).rand(10, 99); return $newName.$oldType; } }