2014-09-02 83 views
0

我遇到了生成文件的問題。這裏是我的行動:Symfony:強制下載生成的文件

<?php 
public function exportAction() 
{ 
    $this->checkSecurity('EDIT'); 

    $config = $this->getConfiguration(); 
    $resource = $this->findOr404(); 

    $style = $this->render($config->getTemplate('export.css'), array(
     'resource' => $resource 
    )); 

    $response = new Response(); 
    $response->headers->set('Cache-Control', 'private'); 
    $response->headers->set('Content-type', 'plain/text'); 
    $response->headers->set('Content-type', 'application/octet-stream'); 
    $response->headers->set('Content-Disposition', 'attachment; filename="style-' . $resource->getSlug() . '.css";'); 
    $response->sendHeaders(); 
    $response->setContent($style); 

    return $response; 
} 

我的文件下載,但它的內容有開頭:

HTTP/1.0 200 OK 
Cache-Control: no-cache 
Date:   Tue, 02 Sep 2014 09:16:34 GMT 

有誰知道爲什麼嗎?

回答

0

我不使用響應作爲生成的文件下載的回報。

我只需填寫然後一個變量它顯示如下:

$style = $this->render($config->getTemplate('export.css'), array(
    'resource' => $resource 
)); 


    header("Content-Type: text/calendar; filename='style-" . $resource->getSlug() . ".css'"); 
    header('Content-Length: '.strlen($style); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Disposition: inline; filename='style-" . $resource->getSlug() . ".css'"); 
    header("Expires: 0"); 
    header("Cache-Control: no-cache, must-revalidate"); 
    header("Pragma: no-cache"); 

echo $style; 
exit; 

我知道這是不是絕對的物體側的代碼,但它完全適用於產生集成電路的千我們項目的一個內日常的文件

+0

可能重複:http://stackoverflow.com/questions/13010411/symfony2-force-file-download?rq=1 – 2014-09-02 12:04:33

+0

我想你的代碼。該文件不下載。我仍然有「HTTP/1.0 200 OK緩存控制:無緩存日期:星期二,2014年9月02日14:19:10 GMT」顯示在我的屏幕上之前的CSS代碼我想下載 – 2014-09-02 14:20:54

+0

我添加了$迴應 - > sendHeaders()。現在該文件已成功下載,但我仍然有「HTTP/1.0 200 OK Cache-Control:no-cache Date:Wed,02 Sep 2014 14:22:02 GMT」開頭... – 2014-09-02 14:23:55

0

我終於找到了解決方案。我忘了的getContent()上渲染

<?php 
public function exportAction() 
{ 
    $this->checkSecurity('EDIT'); 

    $config = $this->getConfiguration(); 
    $resource = $this->findOr404(); 

    $style = $this->render($config->getTemplate('export.css'), array(
     'resource' => $resource 
    )); 

    $response = new Response(); 
    $response->headers->set('Cache-Control', 'private'); 
    $response->headers->set('Content-type', 'plain/text'); 
    $response->headers->set('Content-type', 'application/octet-stream'); 
    $response->headers->set('Content-Disposition', 'attachment; filename="style-' . $resource->getSlug() . '.css";'); 
    $response->sendHeaders(); 
    $response->setContent($style->getContent()); 

    return $response; 
} 
+0

我很高興你終於找到了,我的方法也可以工作,但我認爲$ style實際上是你的內容變量。 – 2014-09-02 14:35:05