2016-01-21 90 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.'"', 
      ] 
     );