2015-12-02 81 views
1

我使用項目中的OneupUploaderBundle上傳文件。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

那麼,你不能在你的樹枝模板中做到這一點。 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 } 
+0

謝謝。就是這個方法... – gondor