使用此代码制作和下载zip,一切正常,但zip是在Web服务器的根目录下载。我想将它从网上下载到本地机器。
<?php
$dir = 'uploads/';
$bannerName = $_POST['bName'];
$zip_file = $bannerName.'.zip';
// Get real path for our folder
$rootPath = realpath($dir);
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
$htmlContent = $_POST['htmlData'];
$createIndex = "index.html";
$zip->addFromString("index.html", $htmlContent);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
$dirN = "assets/";
// Add current file to archive
$zip->addFile($filePath, $dirN.$relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);
?>
每当用户点击下载按钮时,它应该开始下载创建的zip,目前它将zip保存在服务器的根目录上。