Symfony2强制jpg下载返回损坏的文件 [英] Symfony2 forcing jpg download returns corrupted file
问题描述
关于这个问题的许多帖子中,我终于想出了这个版本的强制下载代码:
Following some of the many posts related to the subject I finally came up with this version of the "force download" code:
public function downloadAction(Request $request){
$filename= 'test.jpg';
$response = new Response();
$response->headers->set('Content-Type','image/jpg');
$response->headers->set('Content-Disposition', 'attachment; filename="' . basename($filename) . '"');
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
return $response;
}
现在,这可以很好的使用zip文件(显然使用正确的内容类型),但是对于jpg,会发生不同的事情。当使用HexCompare来检查原始和下载的JPG时,我发现下载的版本在文件的开头添加了EF BB BF。这似乎足以让Windows图像查看器报告错误的文件错误。
Now, this works fine with zip files (obviously using the right content-type), but for jpg something different happens. When using HexCompare to check both original and downloaded JPG I found that the downloaded version adds "EF BB BF" at the beginning of the file. This seems to be enough for the Windows Image Viewer, which ends reporting a corrupt file error.
另一方面,相同的下载jpg在Adobe Photoshop中完美打开(也许不太严格)?
On the other hand, the same downloaded jpg opens perfectly in Adobe Photoshop (less strict perhaps?)
想法?任何人?
提前感谢
Z
更新:使用此代码下载的Zip文件只能使用WinRAR或WinZIP打开,Windows Explorer Zip Extract显示损坏的文件错误消息。
UPDATE: Downloaded Zip files using this code can only be opened with WinRAR or WinZIP, Windows Explorer Zip Extract shows a Corrupt File Error message.
更新2:好的,我现在知道是BOM问题。现在,如何从file_get_content结果中摆脱那个令人讨厌的EF BB BF?
UPDATE2: OK, I know now is a BOM issue. Now, how can I get rid of that nasty "EF BB BF" from the file_get_content result?
推荐答案
请尝试以下内容建议此处
// Set headers
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', mime_content_type($filename));
$response->headers->set('Content-Disposition', 'attachment; filename="' . basename($filename) . '"');
$response->headers->set('Content-length', filesize($filename));
// Send headers before outputting anything
$response->sendHeaders();
$response->setContent(readfile($filename));
如果您使用apache与mod_xsendfile,请尝试:
If you're using apache with mod_xsendfile, try:
return new Response('', 200, array(
'X-Sendfile' => $filename,
'Content-type' => 'application/octect-stream',
'Content-Disposition' => sprintf('attachment; filename="%s"', $filename)),
// ...
));
如果您使用nginx的X-Accel,请阅读这里。并使用
If you're using nginx's X-Accel read here. and use
return new Response('', 200, array(
'X-Accel-Redirect' => $filename,
'Content-type' => 'application/octect-stream',
'Content-Disposition' => sprintf('attachment; filename="%s"', $filename)),
// ...
));
通过nginx获得更多的控制额外的可用选项是...
to gain more control with nginx additional available options are ...
// ...
'X-Accel-Limit-Rate' => '1024',
'X-Accel-Buffering' => 'yes', // yes|no
'X-Accel-Charset' => 'utf-8',
// ...
这篇关于Symfony2强制jpg下载返回损坏的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!