如何在 Symfony2 中啟動強製檔案下載?

Mary-Kate Olsen
發布: 2024-10-23 13:16:02
原創
519 人瀏覽過

How to Initiate Forced File Downloads in Symfony2?

在 Symfony2 中強製檔案下載

處理下載連結上的使用者點擊事件時,目的是提示使用者儲存檔案。然而,在 Symfony2 中,嘗試啟動檔案下載通常會導致不期望的結果。

一種方法涉及手動指定回應標頭:

<code class="php">    $response = new Response();
    $response->headers->set('Content-type', 'application/octect-stream');
    $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
    $response->headers->set('Content-Length', filesize($filename));</code>
登入後複製

但是,這種方法可能會導致下載顯示 0 位元組檔案大小的對話方塊。

包含 Content-Transfer-Encoding 標頭可以解決此問題:

<code class="php">        $response->headers->set('Content-Transfer-Encoding', 'binary');
        $response->setContent(readfile($filename));</code>
登入後複製

但是,這有時會產生不可讀的字元流。

另一種方法是結合使用 setContent 函數和 file_get_contents() 函數:

<code class="php">    $response->setContent(file_get_contents($filename));</code>
登入後複製

此方法可能會導致與記憶體限制相關的 PHP 錯誤。

至避免這些問題,請考慮使用 BinaryFileResponse 類別:

<code class="php">use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

$response = new BinaryFileResponse($file);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);</code>
登入後複製

此解決方案簡單且輕鬆,有助於實現所需的檔案下載行為。

以上是如何在 Symfony2 中啟動強製檔案下載?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!