Symfony php zip文件下载时没有字节
我正在尝试使用symfony2创建和下载一个zip文件。当我创建zip文件时,一切看起来都很棒。当我在服务器上查看zip文件时,一切看起来都很好。当我下载zip文件时,它没有字节。我的回答出了什么问题Symfony php zip文件下载时没有字节,php,symfony,Php,Symfony,我正在尝试使用symfony2创建和下载一个zip文件。当我创建zip文件时,一切看起来都很棒。当我在服务器上查看zip文件时,一切看起来都很好。当我下载zip文件时,它没有字节。我的回答出了什么问题 // Return response to the server... $response = new Response(); $response->setStatusCode(200); $response->headers->set('Cont
// 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文档: 在vanilla 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.'"',
]
);
如果文件较大,这将杀死PHP