Symfony2 创建和下载 zip 文件 [英] Symfony2 create and download zip file
本文介绍了Symfony2 创建和下载 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个应用程序可以上传一些文件,然后我可以将其压缩为 zip 文件并下载.
I have one application that upload some files and then I can compress as zip file and download.
导出操作:
public function exportAction() {
$files = array();
$em = $this->getDoctrine()->getManager();
$doc = $em->getRepository('AdminDocumentBundle:Document')->findAll();
foreach ($_POST as $p) {
foreach ($doc as $d) {
if ($d->getId() == $p) {
array_push($files, "../web/".$d->getWebPath());
}
}
}
$zip = new \ZipArchive();
$zipName = 'Documents-'.time().".zip";
$zip->open($zipName, \ZipArchive::CREATE);
foreach ($files as $f) {
$zip->addFromString(basename($f), file_get_contents($f));
}
$response = new Response();
$response->setContent(readfile("../web/".$zipName));
$response->headers->set('Content-Type', 'application/zip');
$response->header('Content-disposition: attachment; filename=../web/"'.$zipName.'"');
$response->header('Content-Length: ' . filesize("../web/" . $zipName));
$response->readfile("../web/" . $zipName);
return $response;
}
一切正常,直到行标题.每次我去这里时,我都会收到错误消息:警告:readfile(../web/Documents-1385648213.zip):无法打开流:没有这样的文件或目录"
everything is ok until the line header. and everytime I'm going here I got the error: "Warning: readfile(../web/Documents-1385648213.zip): failed to open stream: No such file or directory"
怎么了?
以及为什么当我上传文件时,这些文件具有 root 权限,而我创建的 zip 文件也是如此.
and why when I upload the files, this files have root permissions, and the same happens for the zip file that I create.
推荐答案
已解决:
$zip->close();
header('Content-Type', 'application/zip');
header('Content-disposition: attachment; filename="' . $zipName . '"');
header('Content-Length: ' . filesize($zipName));
readfile($zipName);
显然关闭文件很重要;)
apparently closing the file is important ;)
这篇关于Symfony2 创建和下载 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文