[英]Symfony php zip file has zero bytes when downloaded
我正在嘗試使用symfony2創建並下載一個zip文件。 創建zip文件時,一切看起來都很不錯。 當我在服務器上查看zip文件時,一切看起來都很不錯。 當我下載該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;
您可能錯過了文件內容。
試試看
$response = new Response(file_get_contents($zipFile));
代替
$response = new Response();
希望這個幫助
您要做的是發送包含標頭的響應。 僅標題。 您也需要發送文件。
查看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;
希望這能完全回答您的問題。
接近目標!
// 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;
或更簡單
return new Response(
file_get_contents($zipFile),
200,
[
'Content-Type' => 'what you want here',
'Content-Disposition' => 'attachment; filename="'.$fileName.'"',
]
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.