我在项目中使用OneupUploaderBundle来上传文件。
我的问题是:
如何在我的树枝模板中从UploadListener渲染response.msg?我如何评估我的回复。
https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/response.md
// service.yml
acme.upload_listener:
class: Acme\AcmeBundle\EventListener\UploadListener
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({});
我找不到例子......
感谢您的帮助。
答案 0 :(得分:0)
嗯,你不能在你的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 Foo\BarBundle\EventListener;
use Oneup\UploaderBundle\Event\PostPersistEvent;
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;
}
}
在您的services.yaml:
中# Event listener to handle uploaded files
foobar.upload_listener:
class: Foo\BarBundle\EventListener\UploadListener
tags:
- { name: kernel.event_listener, event: oneup_uploader.post_persist.default_uploader, method: onUpload }