Symfony2 forcing jpg download returns corrupted file

女生的网名这么多〃 提交于 2019-12-25 07:38:32

问题


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;
} 

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.

On the other hand, the same downloaded jpg opens perfectly in Adobe Photoshop (less strict perhaps?)

Ideas? anyone?

Thanks in advance.

Z

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.

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?


回答1:


Please try the following as suggested here

// 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));

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)),
     // ...
));    

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)),
    // ...
));    

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',
 // ...


来源:https://stackoverflow.com/questions/16719271/symfony2-forcing-jpg-download-returns-corrupted-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!