2016-01-21 58 views
2

我正在尝试使用symfony2下载zip文件&。当我创建zip文件时,一切看起来都很棒。当我查看服务器上的zip文件时,一切看起来都很棒。当我下载zip文件时,它有零字节。我的回应有什么问题?Symfony php zip文件下载时为零字节

// Return response to the server... 
    $response = new Response(); 
    $response->setStatusCode(200); 
    $response->headers->set('Content-Type', 'application/zip'); 
    $response->headers->set('Content-Disposition', 'attachment; filename="'.$zipName.'"'); 
    $response->headers->set('Content-Length', filesize($zipFile)); 
    return $response; 

回答

2

可能是您错过了文件内容。

尝试用

$response = new Response(file_get_contents($zipFile)); 

,而不是

$response = new Response(); 

希望这有助于

+0

这将在大文件的情况下杀死PHP – JesusTheHun

2

你要做的就是发送包含头文件的响应。只有标题。你也需要发送文件。

看Symfony的文档:http://symfony.com/doc/current/components/http_foundation/introduction.html#serving-files

在香草PHP要:

header('Content-Description: File Transfer'); 
header('Content-Transfer-Encoding: binary'); 
header("Content-Disposition: attachment; filename=$filename"); 

然后读取文件的输出。

$handle = fopen('myfile.zip', 'r');  

while(!eof($handle)) { 
echo fread($handle, 1024); 
} 

fclose($handle); 

随着文档,你可以轻松地找到解决办法;)

编辑:

当心你的文件的大小。使用file_get_contents或stream_get_contents,您将整个文件加载到PHP的内存中。如果文件很大,则可以达到php的内存限制,并最终导致严重错误。 与fread一起使用循环,只能将1024字节的数据块加载到内存中。

编辑2:

我有一些时间来测试,这完美的作品大文件:

$response = new BinaryFileResponse($zipFile); 
$response->setStatusCode(200); 
$response->headers->set('Content-Type', 'application/zip'); 
$response->headers->set('Content-Disposition', 'attachment; filename="'.basename($zipFile).'"'); 
$response->headers->set('Content-Length', filesize($zipFile)); 

return $response; 

希望这完全回答你的问题。

1

靠近目标!

// Return response to the server... 
    $response = new Response(); 
    $response->setContent(file_get_contents($zipFile)); 
    $response->setStatusCode(200); 
    $response->headers->set('Content-Type', 'application/zip'); 
    $response->headers->set('Content-Disposition', 'attachment; filename="'.$zipName.'"'); 
    $response->headers->set('Content-Length', filesize($zipFile)); 
    return $response; 

或者simplier

return new Response(
      file_get_contents($zipFile), 
      200, 
      [ 
       'Content-Type'  => 'what you want here', 
       'Content-Disposition' => 'attachment; filename="'.$fileName.'"', 
      ] 
     );