0

在我的 symfony2 应用程序中,我允许用户下载一些文件:

class FileController extends Controller
{
     ...

     public function downloadFilesAction()
     {
        //This will serve a page listing all downloadable files and their url

     }

     public function downloadFileAction($file_id)
     {
         //This will be requested from the page served 
         //in the above "downloadFilesAction()"

         try {
             // Some processing goes here ...
         }
         catch (\Exception $e) 
         {
             $this->get('session')->getFlashBag()->add('error', 'Error occurred');
             return $this->forward('MyBundle:File:downloadFiles');
         }

         //get file content into &content variable

         $headers = array(
             'Content-Type' => 'text/csv;',
             'Content-Disposition' => "attachment; filename*=UTF-8''downloadedfile.csv",
         ); 

         return new Response($content, 200, $headers);
     }
}

让我们假设第一次出现错误并显示闪烁错误消息;第二次下载成功。问题是在第二次请求时,flash 消息仍然停留在页面上。下载成功后,如何摆脱 Flash 消息?

4

2 回答 2

0

要重置闪存包,您可以重定向用户而不是转发操作:

return $this->redirect($this->generateUrl('download_files_route'));
于 2014-03-19T15:17:03.443 回答
0

get('error')只需在您的第一个内部使用清除 flashbag 的现有消息即可downloadFileAction()

请注意, usingFlashBag->clear()将取消设置所有消息(这不是必需的)。

public function downloadFileAction($file_id)
{
    $flashBag = $this->get('session')->getFlashBag();
    $flashBag->get('error'); // clear the error message

    try {
         // ...
    }
    catch (\Exception $e) 
    {
        $flashBag->add('error', 'Error occurred');

        return $this->forward('MyBundle:File:downloadFiles');
    }

    // ...
于 2014-03-19T10:10:31.440 回答