- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
<分区>
我在文件上传进度方面遇到了一些问题。我在 xampp、windows 7 上使用 zend framework 2.2。
表格(SignupForm):
namespace Application\Form;
use Zend\Form\Form;
use Zend\Form\Element;
class SignupForm extends Form
{
public function __construct($name = null)
{
$this->add(array(
'name' => 'username',
'type' => 'Text',
'options' => array(
'label' => 'Username',
'label_attributes' => array(
'class' => 'formlabel',
),
),
));
$this->add(array(
'type' => 'Zend\Form\Element\File',
'name' => 'fileupload',
'attributes' => array(
'id' => 'fileupload',
),
'options' => array(
'label' => 'Photo',
'label_attributes' => array(
'class' => 'formlabel',
),
),
));
}
}
Controller (IndexController):
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\Signup;
use Application\Form\SignupForm;
class IndexController extends AbstractActionController {
protected $userTable;
protected $userTablee;
public function getSignTable($table, $object) {
if (!$this->$object) {
$sm = $this->getServiceLocator();
$this->$object = $sm->get($table);
}
return $this->$object;
}
public function indexAction() {
return new ViewModel();
}
public function signupAction() {
$form = new SignupForm();
$form->get('submi')->setValue('Submit');
$request = $this->getRequest();
if ($request->isPost()) {
$album = new Signup();
$t = $this->getSignTable('dbAdapter\dbtable=user', 'userTablee');
$form->setInputFilter($album->getInputFilter($t));
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$album->exchangeArray($form->getData());
$this->getSignTable('Album\Model\AlbumTable\dbtable=user', 'userTable')->saveUser($album);
//--------------------------------------------------file upload progress--------------------
// Form is valid, save the form!
if (!empty($post['isAjax'])) {
return new JsonModel(array(
'status' => true,
'redirect' => $this->url()->fromRoute('upload-form
/success'),
'formData' => $album,
));
} else {
// Fallback for non-JS clients
return $this->redirect()->toRoute('upload-form
/success');
}
} else {
if (!empty($post['isAjax'])) {
// Send back failure information via JSON
return new JsonModel(array(
'status' => false,
'formErrors' => $form->getMessages(),
'formData' => $form->getData(),
));
}
$filter = new \Zend\Filter\File\RenameUpload("./public/photo/" . $album->username);
$filter->setUseUploadExtension(true);
$filter->setRandomize(true);
$filter->filter($data['fileupload']);
}
}
return array('form' => $form);
}
public function uploadProgressAction()
{
$id = $this->params()->fromQuery('id', null);
$progress = new \Zend\ProgressBar\Upload\SessionProgress();
return new \Zend\View\Model\JsonModel($progress->getProgress($id));
}
}
模型(注册):
namespace Application\Model;
use Zend\Http\PhpEnvironment\Request;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator;
class Signup implements InputFilterAwareInterface {
public $username;
public $fileupload;
protected $inputFilter;
public function exchangeArray($data) {
$this->username = (!empty($data['username'])) ? $data['username'] : null;
$this->fileupload = (!empty($data['fileupload'])) ? $data['fileupload'] : null;
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception("Not used");
}
public function getInputFilter($adapter = null) {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'fileupload',
'required' => true,
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
View (索引):
<?php
$this->plugin('basePath')->setBasePath('/zendtest/public');
$title = 'Signup';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<div class="signupform">
<?php
$form->prepare();
$form->setAttribute('action', $this->url('signup', array('action' => 'signup')));
$form->setAttribute('method', 'post');
$form->setAttribute('class', 'signform');
$form->setAttribute('enctype', 'multipart/form-data');
echo $this->form()->openTag($form);
$errmsg = $form->getMessages();
?>
<!-- ----------------------------------------username -->
<div class="signupformrow">
<?php
echo $this->formLabel($form->get('username'));
echo $this->formInput($form->get('username'));
if ($errmsg) {
if (isset($errmsg['username'])) {
foreach ($errmsg['username'] as $key => $value) {
?>
<span class="formerror">
<?php
if ($key == "isEmpty") {
echo"Username required";
} else {
echo $value;
}
?>
</span>
<?php
}
} else {
?>
<span class="formins"><img src="<?php echo $this->basePath('/images/tick.png'); ?>" /></span>
<?php
}
} else {
?>
<span class="formins">(Username must be 5-69 characters and alphanumeric only)</span>
<?php
}
?>
</div>
<!-- ----------------------------------------file -->
<?php echo $this->formFileSessionProgress(); ?>
<div class="signupformrow">
<?php
echo $this->formLabel($form->get('fileupload'));
echo $this->formFile($form->get('fileupload'));
if ($errmsg) {
if (isset($errmsg['fileupload'])) {
print_r($errmsg['fileupload']);
foreach ($errmsg['fileupload'] as $key => $value) {
?>
<span class="formerror">
<?php
if ($key == "isEmpty") {
echo'Photo required';
} else {
echo $value;
}
?>
</span>
<?php
}
}
}
?>
</div>
<!-- ----------------------------------------submit -->
<div class="signupformrow">
<label class="formlabel"></label>
<button>Submit</button>
</div>
<?php
echo $this->form()->closeTag();
?>
<!-- ---------------------------------------file upload progressbar-------------------------------------- -->
<div id="progress" class="help-block">
<div class="progress progress-info progress-striped">
<div class="bar"></div>
</div>
<p></p>
</div>
<script src="<?php echo $this->basePath('/js/jquery.min.js'); ?>"></script>
<script src="<?php echo $this->basePath('/js/jquery.form.js'); ?>"></script>
<script>
var progressInterval;
function getProgress() {
// Poll our controller action with the progress id
var url = '<?php echo $this->url('signup') ?>/upload-progress?id=' + $('#progress_key').val();
$.getJSON(url, function(data) {
if (data.status && !data.status.done) {
var value = Math.floor((data.status.current / data.status.total) * 100);
showProgress(value, 'Uploading...');
} else {
showProgress(100, 'Complete!');
clearInterval(progressInterval);
}
});
}
function startProgress() {
showProgress(0, 'Starting upload...');
progressInterval = setInterval(getProgress, 900);
}
function showProgress(amount, message) {
$('#progress').show();
$('#progress .bar').width(amount + '%');
$('#progress > p').html(message);
if (amount < 100) {
$('#progress .progress')
.addClass('progress-info active')
.removeClass('progress-success');
} else {
$('#progress .progress')
.removeClass('progress-info active')
.addClass('progress-success');
}
}
$(function() {
// Register a 'submit' event listener on the form to perform the AJAX POST
$('#signup').on('submit', function(e) {
e.preventDefault();
if ($('#fileupload').val() == '') {
// No files selected, abort
return;
}
// Perform the submit
//$.fn.ajaxSubmit.debug = true;
$(this).ajaxSubmit({
beforeSubmit: function(arr, $form, options) {
// Notify backend that submit is via ajax
arr.push({ name: "isAjax", value: "1" });
},
success: function (response, statusText, xhr, $form) {
clearInterval(progressInterval);
showProgress(100, 'Complete!');
// TODO: You'll need to do some custom logic here to handle a successful
// form post, and when the form is invalid with validation errors.
if (response.status) {
// TODO: Do something with a successful form post, like redirect
// window.location.replace(response.redirect);
} else {
// Clear the file input, otherwise the same file gets re-uploaded
// http://stackoverflow.com/a/1043969
var fileInput = $('#fileupload');
fileInput.replaceWith( fileInput.val('').clone( true ) );
// TODO: Do something with these errors
// showErrors(response.formErrors);
}
},
error: function(a, b, c) {
// NOTE: This callback is *not* called when the form is invalid.
// It is called when the browser is unable to initiate or complete the ajax submit.
// You will need to handle validation errors in the 'success' callback.
console.log(a, b, c);
}
});
// Start the progress polling
startProgress();
});
});
</script>
</div>
模块配置:
<?php
return array(
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/zendtest/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
),
'application' => array(
'type' => 'Literal',
'options' => array(
'route' => '/zendtest/application',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
//===================================signup================================================================
'signup' => array(
'type' => 'segment',
'options' => array(
'route' => '/zendtest/application/signup[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'signup',
),
),
),
), // routes end
), // router ends
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
),
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
'controllers' => array(
'invokables' => array(
'Application\Controller\Index' => 'Application\Controller\IndexController'
),
),
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'application/index/signup' => __DIR__ . '/../view/application/signup/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
);
我的注册页面在“/zendtest/application/signup/”打开。
当我点击提交按钮时没有任何反应。
更新:
如果我使用以下代码,请告诉我如何使用“Zend\ProgressBar\Upload\UploadProgress”将文件上传进度条添加到我的表单中。我应该如何更改 Controller 、模型或 View ?
Controller :
if ($form->isValid()) {
$album->exchangeArray($form->getData());
$album->act_code = Rand::getString(5);
$album->dkey = Rand::getString(5);
$this->getSignTable('Album\Model\AlbumTable\dbtable=user', 'userTable')->saveUser($album);
//==================================================file========================================
$filter = new \Zend\Filter\File\RenameUpload("./public/photo/" . $album->username);
$filter->setUseUploadExtension(true);
$filter->setRandomize(true);
$filter->filter($data['fileupload']);
}
}
过滤和验证模型(Signup.php):
$inputFilter->add(array(
'name' => 'fileupload',
'required' => true,
'validators' => array(
$fileValidator->attach(new \Zend\Validator\File\UploadFile(array(
'messages' => array(
\Zend\Validator\File\UploadFile::NO_FILE => 'Photo required',
),
)
), true)
),
));
View :
<?php echo $this->formFileSessionProgress(); ?>
<div class="signupformrow">
<?php
echo $this->formLabel($form->get('fileupload'));
echo $this->formFile($form->get('fileupload'));
if ($errmsg) {
if (isset($errmsg['fileupload'])) {
print_r($errmsg['fileupload']);
foreach ($errmsg['fileupload'] as $key => $value) {
?>
<span class="formerror">
<?php
if ($key == "isEmpty") {
echo'Photo required';
} else {
echo $value;
}
?>
</span>
<?php
}
}
}
?>
</div>
更新 2:
View :
<div class="signupform">
<?php
$form->prepare();
$form->setAttribute('action', $this->url('signup', array('action' => 'signup')));
$form->setAttribute('method', 'post');
$form->setAttribute('class', 'signform');
$form->setAttribute('id', 'signup');
$form->setAttribute('enctype', 'multipart/form-data');
echo $this->form()->openTag($form);
$errmsg = $form->getMessages();
?>
<!-- ----------------------------------------username -->
<div class="signupformrow">
<?php
echo $this->formLabel($form->get('username'));
echo $this->formInput($form->get('username'));
if ($errmsg) {
if (isset($errmsg['username'])) {
foreach ($errmsg['username'] as $key => $value) {
?>
<span class="formerror">
<?php
if ($key == "isEmpty") {
echo"Username required";
} else {
echo $value;
}
?>
</span>
<?php
}
} else {
?>
<span class="formins"><img src="<?php echo $this->basePath('/images/tick.png'); ?>" /></span>
<?php
}
} else {
?>
<span class="formins">(Username must be 5-69 characters and alphanumeric only)</span>
<?php
}
?>
</div>
<!-- ----------------------------------------file -->
<div class="signupformrow">
<?php
echo $this->formLabel($form->get('fileupload'));
?>
<div class="filediv">
<?php
echo $this->formFile($form->get('fileupload'));
?>
<a onclick="select_file()" class="pure-button upbutton">Choose an Image</a>
<br />
<!--image preview-->
<img id="upimg" name="upimg" src="" style="">
<br />
</div>
<?php
if ($errmsg) {
if (isset($errmsg['fileupload'])) {
foreach ($errmsg['fileupload'] as $key => $value) {
?>
<span class="formerror">
<?php
if ($key == "isEmpty") {
echo'Photo required';
} else {
echo $value;
}
?>
</span>
<?php
}
}
}
?>
</div>
<!-- ----------------------------------------submit -->
<div class="signupformrow">
<label class="formlabel"></label>
<?php
echo $this->formSubmit($form->get('submi'));
?>
</div>
<?php
echo $this->form()->closeTag();
?>
</div>
<!--progress bar-->
<div class="progress">
<div class="barrr"></div>
<div class="percenttt">0%</div>
</div>
<script src="<?php echo $this->basePath('/js/jquery.min.js'); ?>"></script>
<script src="<?php echo $this->basePath('/js/jquery.form.min.js'); ?>"></script>
<script type="text/javascript">
$(document).ready(function() {
/* variables */
var preview = $('#upimg');
var status = $('.status');
var percent = $('.percenttt');
var bar = $('.barrr');
/* only for image preview */
$("#fileupload").change(function(){
preview.fadeOut();
/* html FileRender Api */
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("fileupload").files[0]);
oFReader.onload = function (oFREvent) {
preview.attr('src', oFREvent.target.result).fadeIn();
};
});
/* submit form with ajax request */
$('#signup').ajaxForm({
/* set data type json */
dataType:'json',
/* reset before submitting */
beforeSend: function() {
status.fadeOut();
bar.width('0%');
percent.html('0%');
},
/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
var pVel = percentComplete + '%';
bar.width(pVel);
percent.html(pVel);
},
/* complete call back */
complete: function(data) {
preview.fadeOut(800);
status.html(data.responseJSON.status).fadeIn();
}
});
});
function select_file(){
document.getElementById('fileupload').click();
return false;
}
</script>
表单验证模型(Signup.php):
class Signup implements InputFilterAwareInterface {
public $username;
public $fileupload;
protected $inputFilter;
protected $usernameValidator;
protected $fileValidator;
protected $adapter;
public function exchangeArray($data) {
$this->username = (!empty($data['username'])) ? $data['username'] : null;
$this->fileupload = (!empty($data['fileupload'])) ? $data['fileupload'] : null;
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception("Not used");
}
public function getInputFilter($adapter = null) {
$this->adapter = $adapter;
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$usernameValidator = new \Zend\Validator\ValidatorChain();
$fileValidator = new \Zend\Validator\ValidatorChain();
$inputFilter->add(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
),
'validators' => array(
$usernameValidator->attach(
new \Zend\Validator\NotEmpty(array()), true)
->attach(new \Zend\Validator\Regex(array(
'pattern' => '/^[a-z]+[a-z0-9_]+$/',
'messages' => array(
\Zend\Validator\Regex::INVALID => 'Username is not valid',
\Zend\Validator\Regex::NOT_MATCH => 'Only small alphabet, digit and underscore are allowed. Username must start with an alphabet',
),
)), true)
)
));
$inputFilter->add(array(
'name' => 'fileupload',
'required' => true,
'validators' => array(
$fileValidator->attach(new \Zend\Validator\File\UploadFile(array(
'messages' => array(
\Zend\Validator\File\UploadFile::NO_FILE => 'Photo required',
),
)
), true)
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
它在表单有效时工作,但如果表单有错误(假设“用户名”字段为空)则它不会显示错误消息(应该来自模型“Signup.php”)和进度条即使文件实际上没有上传,仍然显示文件上传进度。
如果我从“index.phtml”中删除以下行并将它们添加到“layout.phtml”的“head”中,那么表单验证有效但文件上传进度条不起作用(表单提交如下正常的 php 形式)。 But the image is shown by the jquery when the image file is selected.
//index.phtml
<script src="<?php echo $this->basePath('/js/jquery.min.js'); ?>"></script>
<script src="<?php echo $this->basePath('/js/jquery.form.min.js'); ?>"></script>
//layout.phtml
<!-- Scripts -->
<?php echo $this->headScript()->prependFile($this->basePath('/js/html5.js'), 'text/javascript', array('conditional' => 'lt IE 9',))
->prependFile($this->basePath('/js/bootstrap.min.js'))
->prependFile($this->basePath('/js/jquery.min.js'))
->prependFile($this->basePath('/js/jquery.form.min.js')) ?>
</head>
我正在开发一个在 gridview 中显示数据表内容的网页。而且,还有一个名为“发送到 Excel”的按钮。如果用户单击此按钮,该程序将开始生成报告(将数据表内容写入 excel 文件)。完成后,会出
理论:我在开始时做出了大约 100 个 promise ,然后使用 Promise.all() 解决它们。 这 100 个 promise 中的每一个依次进行一些异步 REST 调用,其响应可能主要不
在将文件添加到 python 中的 tar 存档时,是否有任何库可以显示进度,或者可以扩展 tarfile 模块的功能来执行此操作? 在理想情况下,我想展示 tar 创建的总体进度以及关于何时完成的预
有没有办法在 Xcode 中更改进度 View 栏的高度? 我正在使用 Xcode 4.3 并且需要一个垂直进度条。我旋转了栏,但现在无法更改高度并且显示为一个圆圈。 还有一种更有效的旋转进度条的方法
您好,我想在栏按钮项上制作未确定的进度 View 。完成后我想让它隐藏,但 hidden() 方法没有像 disabled(Bool) 这样的参数。任务完成后如何隐藏进度 View ? 这就是我要的
我有一个管理员控制的功能(导入数据库)可能需要一些时间才能完成,所以我想在这段时间内向用户显示一些反馈 - 例如进度条,或者只是一些消息。即使在长时间的 Action 中分部分发送页面也足够了。 在
我是一个进步的菜鸟,实际上在基本 block 方面有问题。 下面的问题是在我的 if else 语句中。它在 if, then, else then 时工作正常,但是当我想将多个语句放入 if 部分时
我有一个来自 rsync 命令的日志文件,其中有进度。运行此进度时,会更新同一行上的显示信息。当我捕获此命令的输出时,我得到一个在终端上使用 cat 正常显示的文件(重播所有退格键和重新编辑)但我希望
我需要处理一些数据,每 5-10 秒显示一个进度(我以 % 显示进度,但我也更新了一些图表)。我想在没有多线程的情况下做到这一点。 循环可能相当大。它可以从数百万开始,可以高达数十亿。 我可以使用 G
我正在致力于使用 PHP、HTML 和 JavaScript 制作半直播互联网 channel 。 您可以在此处查看演示:http://mariocreative.host/chanelko/inde
我实际上正在使用图像为“点点点”进度设置动画。我想通过使用下面的代码来使用不透明度。 动画将持续 3 秒,有没有更简单的动画方法? 最佳答案 这是一个快速版本,它会在控
我写了这个程序,它返回用户插入的最大整数。现在,我希望程序返回第二大整数。我创建了一个新变量(称为“状态”),该变量应该在每次循环重复时增加 1 个单位。然后,在中断条件发生后,我将在状态变量中后退
我正在制作一个需要保存进度的java游戏。但我不想让外部文件保存进度(像《我的世界》这样的游戏有一个存储文件的“保存”目录)。所以基本上我希望它存储一些数据,当用户退出并再次返回时可以检索这些数据。比
我正在使用 forEach_root 方法在 Android 上计算图像。 RenderScript RS=RenderScript.create(context); Allocation inPix
我希望这个进度 View 在完成后基本上“重置”。 尝试将计数重置为 0,它确实重置了,但是对于每次重置,计时器只会变得越来越快。 .h @property (nonatomic, strong) N
我不确定这是否可能。当您单击“提交”按钮时,似乎有一种方法可以做到这一点。 private Button getButton(String id) { return new AjaxButto
我找不到关于如何在迭代循环时更新 UIProgressbar 进度的明确答案,例如: for (int i=0;i
我正在尝试在 Xcode 中翻转 UIProgressView 180,同时我正在尝试缩放进度 View 。在我添加翻转之前缩放效果很好,然后缩放不再起作用。有什么建议么?谢谢! [self.seco
我目前正在通过评估 prepareForSegue 中的 segue.identifier 动态加载新 View : - (void)prepareForSegue:(UIStoryboardSegu
当任意进程发生时,我需要在屏幕上为用户提供状态。我无法知道需要多长时间。我怎样才能永远增加 progressView (当它接近 1 时它会减慢)。 最佳答案 This如果您愿意更换进度 View ,
我是一名优秀的程序员,十分优秀!