Symfony2 forcing jpg download returns corrupted fi

2019-08-28 00:04发布

问题:

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