Symfony/PHP二维码下载异常:文件名无扩展名且为GUID
问题
在Symfony框架(或其组件运行环境)下,我用PHP生成二维码后提供给设计部门下载,遇到两个问题:
- 下载的文件没有扩展名
- 文件名变成了GUID格式(例如
aebceb64-c8e1-48d6-b04b-69d4e2959f75)
我需要让下载的文件名为cp_qrcode.eps,当前的实现代码如下:
public function downloadQrCode() { $filePath = __DIR__ . '/../../../../../../var/temp/cp_qrcode.eps'; if (!file_exists($filePath)) { header('HTTP/1.1 404 Not Found'); exit; } if (ob_get_level()) { ob_flush(); flush(); } header('Content-Type: application/postscript'); header('Content-Disposition: attachment; filename="cp_qrcode.eps"'); header('Content-Length: ' . filesize($filePath)); return readfile($filePath); }
补充:客户端接收到的响应头截图:
解决方案
问题根源在Content-Disposition响应头的写法上——你用了HTML实体"来包裹文件名,但HTTP响应头不需要做HTML转义,直接用双引号即可。
修改后的手动header写法代码:
public function downloadQrCode() { $filePath = __DIR__ . '/../../../../../../var/temp/cp_qrcode.eps'; if (!file_exists($filePath)) { header('HTTP/1.1 404 Not Found'); exit; } if (ob_get_level()) { ob_flush(); flush(); } header('Content-Type: application/postscript'); // 直接用双引号包裹文件名,去掉HTML实体转义 header('Content-Disposition: attachment; filename="cp_qrcode.eps"'); header('Content-Length: ' . filesize($filePath)); return readfile($filePath); }
另外,在Symfony环境下更推荐用框架自带的BinaryFileResponse处理文件下载,它会自动处理响应头、缓存、输出等细节,避免手动操作header可能出现的疏漏:
use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\Response; public function downloadQrCode() { $filePath = __DIR__ . '/../../../../../../var/temp/cp_qrcode.eps'; if (!file_exists($filePath)) { return new Response('文件不存在', 404); } $response = new BinaryFileResponse($filePath); $response->setContentDisposition( ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'cp_qrcode.eps' ); return $response; }
两种方式都能让浏览器正确识别文件名和扩展名,下载的文件会是你期望的cp_qrcode.eps。
内容的提问来源于stack exchange,提问作者Vischi
相关产品推荐
相关产品推荐

