【问题标题】:Symfony2 forcing jpg download returns corrupted fileSymfony2 强制 jpg 下载返回损坏的文件
【发布时间】:2013-05-19 03:04:50
【问题描述】:

根据与该主题相关的许多帖子中的一些,我终于想出了这个版本的“强制下载”代码:

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 Image Viewer 来说似乎已经足够了,它会报告损坏的文件错误。

另一方面,同样下载的 jpg 在 Adob​​e Photoshop 中完美打开(也许不那么严格?)

想法?有人吗?

提前致谢。

Z

更新:使用此代码下载的 Zip 文件只能用 WinRAR 或 WinZIP 打开,Windows 资源管理器 Zip 提取显示损坏文件错误消息。

UPDATE2:好的,我现在知道是 BOM 问题。现在,我怎样才能从 file_get_content 结果中去掉那个讨厌的“EF BB BF”?

【问题讨论】:

    标签: symfony download jpeg byte-order-mark corrupt


    【解决方案1】:

    请按照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));
    

    如果您使用带有 mod_xsendfile 的 apache,请尝试:

    return new Response('', 200, array(
        'X-Sendfile'          => $filename,
        'Content-type'        => 'application/octect-stream',
        'Content-Disposition' => sprintf('attachment; filename="%s"', $filename)),
         // ...
    ));    
    

    如果您使用的是 nginx 的 X-Accel,请阅读 here。并使用

    return new Response('', 200, array(
        'X-Accel-Redirect'    => $filename,
        'Content-type'        => 'application/octect-stream',
        'Content-Disposition' => sprintf('attachment; filename="%s"', $filename)),
        // ...
    ));    
    

    要使用 nginx 获得更多控制权,其他可用选项是 ...

    // ...
    'X-Accel-Limit-Rate' => '1024',
    'X-Accel-Buffering'  => 'yes',  // yes|no
    'X-Accel-Charset'    => 'utf-8',
     // ...
    

    【讨论】:

    • 不工作 nifr。使用这种方法,下载的文件会变大几百 KB,但输出仍然损坏,即使对于 Photoshop 也是如此。使用原始代码下载的文件在 Photoshop 中正确打开。
    • 注意:原始测试 jpg 文件只有 633KB,可以在 Windows 7 Image Viewer 中正常打开。对 11KB 1x1pix 文件进行了一些测试,结果相同。
    • 其实 nifr,那是我使用的第一个代码。从那个确切的帖子中获取它。结果完全相同。继续在下载文件的开头添加“EF BB BF”。 ...让我发疯。
    • 你试过 xsendfile / x-accel 吗?无论如何它更好,因为该文件直接由您的网络服务器提供。或者这不是一个选择?您是否检查了代码中的不可见字符并纠正了 utf-8 编码?
    • 不是一个选项,也无法使用 apache。 UTF-8 编码正确,不可打印字符检查也是如此。继续使用其他文件格式和大小进行测试,结果相同。 “EF BB BF”的区别。代码再简单不过了,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2013-03-31
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    相关资源
    最近更新 更多