我正在尝试下载zip文件。所以我尝试制作这样的代码:
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$zipFilePath = $root . '/' . $zipName;
// prepare BinaryFileResponse
$response = new BinaryFileResponse($zipFilePath);
$response->trustXSendfileTypeHeader();
$response->headers->set('Cache-Control', 'public');
$response->headers->set('Content-type', 'application/zip');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$zipName,
iconv('UTF-8', 'ASCII//TRANSLIT', $zipName)
);
return $response;
}
我认为这是成功的。但是,当我尝试打开zip文件时,出现类似这样的错误An error occurred while loading the archive.
然后我试着像这样制作代码
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
header('Content-Type', 'application/zip');
header('Content-disposition: attachment; filename="' . $zipName . '"');
header('Content-Length: ' . filesize($zipName));
readfile($zipName);
}
但我一无所获。当我改变它时也会发生同样的事情:
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
header("HTTP/1.1 303"); // 303 is technically correct for this type of redirect
header("Location: http://{$_SERVER['HTTP_HOST']}/" . $fileName);
}
有没有人可以帮我解决这个下载zip文件的问题?
答案 0 :(得分:2)
An error occurred while loading the archive.
是因为:
zip
文件。zip
文件已损坏或遗失。sudo apt-get update
客户端,(连接或程序错误)或文件本身存在问题。尝试使用另一台PC打开文件。