我在项目中使用OneupUploaderBundle上传文件。
我的问题是:
如何在我的小树枝模板中呈现来自UploadListener的response.msg?我如何评估我的反应。
https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/response.md
//service.yml
acme.upload_listener:
class: AcmeAcmeBundleEventListenerUploadListener
arguments: ["@doctrine.orm.entity_manager"]
tags:
- { name: kernel.event_listener, event: oneup_uploader.post_persist, method: onUpload }
//UploadListener.php
class UploadListener
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function onUpload(PostPersistEvent $event)
{
$file = $event->getFile();
$session = $event->getRequest()->getSession();
$session->set('file', $file->getPathName());
$response = $event->getResponse();
$response['msg'] = "File stored in session";
=> show response.msg in my twig-template. But how?
}
}
//JS(在树枝模板中)
$('#fileupload').fileupload({});
我没有找到任何例子。。。
谢谢你的帮助。
好吧,你不能在你的Twig模板中这样做。Twig模板在页面加载时呈现,文件上传使用Ajax完成。您所能做的就是用javascript修改DOM。
例如:
$('#fileupload').fileupload({}).bind('fileuploaddone', function (e, data) {
$("body").prepend('<p>File stored in session</p>');
});
您也可以将一些数据发送回客户端:
$('#fileupload').fileupload({}).bind('fileuploaddone', function (e, data) {
if (data.result.filename != undefined) {
$("body").prepend('<p>File ' + data.result.filename + ' stored in session</p>');
}
});
但为了做到这一点,您需要为oneup_uploader.post_persist
事件创建一个事件侦听器,该侦听器将把文件名和响应一起发送回,如您链接到的文档中所述。
<?php
namespace FooBarBundleEventListener;
use OneupUploaderBundleEventPostPersistEvent;
class UploadListener
{
public function onUpload(PostPersistEvent $event)
{
$request = $event->getRequest();
$files = $request->files->get('files');
$response = $event->getResponse();
$filename = $files[0]->getClientOriginalName();
$response['filename'] = $filename;
}
}
在您的服务。yaml:
# Event listener to handle uploaded files
foobar.upload_listener:
class: FooBarBundleEventListenerUploadListener
tags:
- { name: kernel.event_listener, event: oneup_uploader.post_persist.default_uploader, method: onUpload }