创建和下载 Zip 文件 (maennchen/ZipStream-PHP) [英] Create and Download Zip File (maennchen/ZipStream-PHP)
本文介绍了创建和下载 Zip 文件 (maennchen/ZipStream-PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的项目中,我们使用了 maennchen/ZipStream-PHP 包.现在我正在尝试创建和下载 zip 文件,但是当我打开 zip 文件时出现空存档"错误.
In my project we used maennchen/ZipStream-PHP bundle. Now I'm trying to create and download zip file, but when I open the zip file I have an error "empty archive".
return new StreamedResponse(function() use ($filenames, $logger) {
$filename = 'example.zip';
$opt = new ArchiveOptions();
$opt->setContentDisposition("attachment;filename=\"$filename\"");
$opt->setContentType('application/octet-stream');
$opt->setEnableZip64(false);
$opt->setFlushOutput(true);
$opt->setSendHttpHeaders(true);
$zip = new ZipStream($filename, $opt);
foreach ($filenames as $f) {
if (true === file_exists($f)) {
try {
$zip->addFileFromPath(basename($f), $f);
} catch (\Exception $exception) {
$logger->error($exception->getMessage());
}
} else {
$logger->error(sprintf('File %s does not exist.', $f));
}
}
$zip->finish();
});
如果我转储 $zip 则文件参数为空.我认为 addFile 方法不起作用.
If I dump $zip then the file argument is empty. I think the addFile method does not work.
你能帮我吗?
提前致谢.
推荐答案
Symfony 的 StreamedResponse 已经在发送标头,所以你不应该在流"中覆盖它们
Symfony's StreamedResponse is sending the headers already, so you should not override them inside the "stream"
试试这个;
return new StreamedResponse(function() use ($filenames, $logger) {
$opt = new \ZipStream\Option\Archive();
$opt->setZeroHeader(true);
$opt->setEnableZip64(false);
$zip = new ZipStream(null, $opt);
foreach ($filenames as $f) {
if (true === file_exists($f)) {
try {
$zip->addFileFromPath(basename($f), $f);
} catch (\Exception $exception) {
$logger->error($exception->getMessage());
}
} else {
$logger->error(sprintf('File %s does not exist.', $f));
}
}
$zip->finish();
},
200,
[
'Content-Disposition' => 'attachment;filename="example.zip"',
'Content-Type' => 'application/octet-stream',
]);
这篇关于创建和下载 Zip 文件 (maennchen/ZipStream-PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文