標籤:zendframework2 檔案上傳 檔案上傳進度 upload php
修改php.ini以適應檔案的要求:
//php.inifile_uploads = Onpost_max_size = 600Mupload_max_filesize = 600Msession.upload_progress.enabled = Onsession.upload_progress.freq = "1%"session.upload_progress.min_freq = "1"
以上我們限制了檔案大小限制在不超過600MB。
關於檔案上傳進度的擷取方式,zf2提供了三個類:
Zend\Progressbar\Upload\ApcProgressZend\ProgressBar\Upload\SessionProgressZend\Progressbar\Upload\UploadProgress
其中SessionProcess要求php5.4以上,本文以SessionProcess為例,其他2個使用方法一樣。
首先建立檔案上傳的From:
//Test/Form/TestForm.php<?phpnamespace Test\Form;use Zend\Form\Form;use Zend\InputFilter\InputFilter;use Zend\InputFilter\InputFilterAwareInterface;use Zend\InputFilter\InputFilterInterface;use Zend\InputFilter\InputFilterProviderInterface;use Zend\Validator\File\Extension; use Zend\Validator\File\Size;use Zend\Validator\File\ImageSize;use Zend\Validator\File\MimeType;use Zend\Filter\File\RenameUpload;class TestForm extends Form implements InputFilterProviderInterface{ protected $inputFilter; public function __construct($name = null) { parent::__construct($name?$name:'test'); //添加一個文字框 $this->add(array( 'name' => 'userName', 'type' => 'Text', 'options' => array( 'label' => 'name:', ), 'attributes' => array( 'size' => 60, 'maxlength' => 100, ), )); //添加檔案上傳input $this->add(array( 'name' => 'u', 'type' => 'File', 'options' => array( 'label' => 'file:', ), 'attributes' => array( 'id' => 'u_e', ), )); //提交按鈕 $this->add(array( 'name' => 'send', 'type' => 'Submit', 'attributes' => array( 'value' => 'ok', ), )); } public function getInputFilterSpecification() { //檔案上傳後儲存到臨時目錄的filter $renameUpload = new RenameUpload(array( "target" => __DIR__."/../../../../../uploads", "randomize" => true, "use_upload_name" => true, )); //驗證副檔名 $extention = new Extension('png,jpeg,jpg,bmp,gif,mp4'); //驗證檔案大小 $size = new Size(array('min'=>'1kB', 'max'=>'600MB')); //驗證檔案MIME類型 $mime = new MimeType(array('image/png','image/jpeg','image/jpg','image/bmp','image/gif','video/mp4','enableHeaderCheck' => true)); return array( 'userName' => array( 'required' => true, 'filters' => array( array('name' => 'StringTrim'), array('name' => 'StringToLower'), ), 'validators' => array( array('name' => 'NotEmpty'), array('name' => 'Alnum'), array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 3, 'max' => 256, ), ), array( 'name' => 'Db\NoRecordExists', 'options' => array( 'table' => 'user', 'field' => 'name', 'adapter' => $this->adapter, ), ), ), ), 'u' => array( 'required' => true, 'filters' => array( $renameUpload, ), 'validators' => array( $extention, $size, //$imgSize, $mime, ), ), ); }}
然後建立view:
//Test/view/test/test/testform.phtml<?php$this->tform->setAttribute('action', $this->url('test', array('action' => 'testform')));$this->tform->setAttribute('method', 'POST');$this->tform->prepare();echo "<div class='tf'>";echo '<div>'.$this->form()->openTag($this->tform).'</div>';//擷取檔案上傳進度必須要使用該view helper,formFileSessionProgress會建立一個id為progress_key的hidden的input記錄檔案上傳進度擷取需要的id//SessionProgress對應formFileSessionProgress,ApcProgress對應formFileApcProgress,UploadProgress對應formFileUploadProgressecho $this->formFileSessionProgress();//文字框echo '<div>'.$this->formRow($this->tform->get('userName')).'</div>';//檔案input//存在這樣的情況:使用者第一次提交後,檔案上傳了並檢驗通過了,但是文字框檢驗不過,此時,不需要使用者重新再上傳一次檔案,所以,在此情況下將檔案input隱藏起來echo '<div '.($this->tempFile?'style="display:none"':'').'>'.$this->formRow($this->tform->get('u')).'</div>';if ($this->tempFile){ echo '<div>'.$this->tempFile['name'].'</div>';}else{ //上傳進度顯示 echo '<div><span style="display:block; float:left;">process:</span><span id="proc" style="display:block; margin-left:60px; width:60px; height: 30px; background-color: #dddddd;"></span></div>';}echo '<div>'.$this->formRow($this->tform->get('send')).'</div>';echo '<div>'.$this->form()->closeTag().'</div>';echo "</div>";echo "<hr />";?><!-- 以下指令碼用於定時擷取並顯示上傳進度 --><script> var progressInterval;function getProgress() { var ul = '/test/uploadprogress?id='+$("#progress_key").val();//上傳進度通過控制器test/uploadprogress擷取 $.ajax({ type : "GET", url : ul, dataType : "json", success : function(data, textStatus) { if (!data.done) { var value = Math.floor((data.current / data.total) * 100); showProgress(value); } else { showProgress(100); clearInterval(progressInterval); } }, error : function(r, t, r){ } });}function startProgress() { showProgress(0); progressInterval = setInterval(getProgress, 400);}function showProgress(amount) { $('#proc').html(amount+"%");}$(document).ready( function(){ $('#test').submit(startProgress); });</script>
最後是控制器:
//Test/Controller/TestController.php<?phpnamespace Test\Controller;use Zend\Mvc\Controller\AbstractActionController;use Zend\Session\Storage\SessionArrayStorage;use Zend\ProgressBar\Upload\SessionProgress;use Zend\View\Model\JsonModel;use Test\Form\TestForm;class TestController extends AbstractActionController { public function testformAction() { $form = new TestForm(); $inputFilter = $form->getInputFilter(); $sessionKey = 'uploadedTempFile'; $sessionStorage = new SessionArrayStorage();//session儲存物件,檔案上傳成功並檢驗成功後,將資訊儲存進session,避免使用者再次重新上傳檔案 $tempFile = null; if ($sessionStorage->offsetExists($sessionKey)){ $tempFile = $sessionStorage->offsetGet($sessionKey); } if ($this->getRequest()->isPost()){//使用者提交了表單,處理表單資料 $postData = array_merge_recursive(//檔案資訊合并到postdata數組 $this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray() ); if (isset($tempFile)) {//本次提交不是首次提交,並且session中有使用者上傳的檔案的快取資料 if (!empty($postData['u']['name'])){//使用者重新上傳了檔案,則原來緩衝的檔案要清除 $sessionStorage->offsetUnset($sessionKey); $tempFile = null; }else{//使用者沒有上傳新檔案,所以,檢驗表單時不檢驗file元素 $inputFilter->get('u')->setRequired(false); } } $form->setData($postData); if ($form->isValid()) {//表單檢驗成功 $data = $form->getData(); if (empty($data['u']) && $tempFile){//使用者沒有上傳新檔案,所以,使用session中緩衝的檔案 $data['u'] = $tempFile; $fileName = $data['u']['name']; $fileMIMEType = $data['u']['type']; $tmpFilePathName = $data['u']['tmp_name']; $fileSize = $data['u']['size']; } //儲存表單 //....... //$this->redirect()->toRoute( } else {//表單元素檢驗失敗 $data = $form->getData(); $fileErrors = $form->get('u')->getMessages(); if (empty($fileErrors) && isset($data['u']['error']) && $data['u']['error'] === UPLOAD_ERR_OK ) { $tempFile = $data['u']; $sessionStorage->offsetSet($sessionKey, $tempFile); } } } else {//不是使用者提交的表單,清空session中的快取資料 if ($sessionStorage->offsetExists($sessionKey)){ $sessionStorage->offsetUnset($sessionKey); } $tempFile = null; } return array( 'tform' => $form, 'tempFile' => $tempFile, ); } //擷取上傳進度的action public function uploadprogressAction() { $id = $this->params()->fromQuery('id', null); $progress = new SessionProgress(); return new JsonModel($progress->getProgress($id)); }}
ZendFramework2學習筆記 檔案上傳、檔案上傳進度