[英]How to force download for remote file in Symfony2?
我的控制器如下所示:
public function downloadAction($filename) {
// Adding url to filename
$path = $this->container->getParameter('remotepath').$filename;
// Checking if file exists
$ch = curl_init($path);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code == 200) {
// Get the file
$file = file_get_contents($path);
// Generate Response
$response = new Response();
$d = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
$response->headers->set('Content-Disposition', $d);
$response->setContent($file);
} else {
$response = new Response();
$response->setContent('File not found. ('.$filename.')');
$response->headers->set('Content-Type', 'text/html');
$response->setStatusCode(404);
}
return $response;
}
我要完成的工作是獲取一個遠程文件(圖像,pdf,...)並強制下載該文件。 但是出於某種原因,Symfony總是在瀏覽器中以純文本(->亂碼)的形式顯示標題和文件內容。
我找不到原因!
編輯:我更改了代碼,以便只創建一個空的Response()並將其返回給控制器。 在使用文件名調用downloadAction時,我將標題內容寫入了瀏覽器窗口。 所以我用Firebug檢查了標題,Symfony似乎用普通的標題響應並打印了我設置為內容的標題。 關於我在做什么錯的任何建議嗎?
通過在控制器方法中執行以下操作,可以使用RedirectResponse完成此操作。
return new RedirectResponse($yourRemoteDownloadUrl);
在此示例中, $yourRemoteDownloadUrl
是一個PDF文件,位於Amazon S3存儲桶中。
可在Symfony 2和3中使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.