如何实现类似的解决方案:
$file = generateCSV();
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename="asd");
header("Pragma: no-cache");
header("Expires: 0");
echo $file;
exit();
使用Symfony Response对象?
现在我有
$file = generateCSV();
$response = new Response($file);
$response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'asd');
$response->headers->set('Content-Disposition', 'text/csv');
$response->headers->set('Pragma', 'no-chache');
$response->headers->set('Expires', '0');
return $response;
但它似乎不起作用,因为它不是发送文件下载,而是将我的文件呈现为浏览器中的文本。
任何帮助将不胜感激。
答案 0 :(得分:2)
您没有指定内容类型。我的下载示例:
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename . '.csv'
);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
答案 1 :(得分:1)
我这样做了:
$response = new StreamedResponse();
$response->setCallback(
/* here you generate your csv file */
);
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set(
'Content-Disposition',
'attachment; filename="file.csv"'
);
return $response;