1

我在我的项目中使用 OneUploaderBundle 来上传文件。

我的问题是:

如何在我的树枝模板中呈现来自 UploadListener 的 response.msg?我如何评估我的反应。

https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/response.md

//服务.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 }

//上传监听器.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({});

我没有找到示例...

谢谢你的帮助。

4

1 回答 1

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 }
于 2015-12-04T17:26:27.680 回答