public function test()
{
$file = request()->file('compress');
if (!$file) {
// 文件上传失败
return 'File upload failed';
}
// 保存上传文件
$savePath = '../uploads/zip/';
$info = $file->validate(['size' => 1567800, 'ext' => 'zip'])->move($savePath, '');
if (!$info) {
// 文件保存失败
return 'File save failed';
}
//解压后保存的文件夹路径
$targetPath = '/www/wwwroot/audios';
$res = unzipFile($info->getRealPath(), $targetPath);
if ($res) {
return '文件保存成功';
}
}
/**
* 解压文件
* @param $UpFilePath 上传文件:"../uploads/zip/test.zip"
* @param $targetPath 解压文件路径:"/www/test/zip"
* @return bool
*/
function unzipFile($upFile, $targetPath)
{
// 创建目录
if (!is_dir($targetPath)) {
mkdir($targetPath, 0777, true);
}
// 解压缩文件夹内的文件
$zip = new \ZipArchive();
$res = $zip->open($upFile);
if ($res === TRUE) {
$zip->extractTo($targetPath);
// 获取解压后的文件夹名称
$extracted_folder_name = $targetPath . '/' . pathinfo($upFile, PATHINFO_FILENAME);
// 将解压后的文件移动到目标文件夹中
$files = @scandir($extracted_folder_name);
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
rename($extracted_folder_name . '/' . $file, $targetPath . '/' . $file);
}
}
// 删除解压后的文件夹
rmdir($extracted_folder_name);
// 删除上传的压缩文件
unlink($upFile);
// 解压缩成功
return true;
} else {
return false;
}
}
public function test12()
{
// 创建一个 ZipArchive 实例
$zip = new \ZipArchive();
// 设置压缩文件名和源文件夹路径
$filename = 'example.zip';
$source = '/www/wwwroot/audios';
// 获取压缩文件的绝对路径和目标目录
$destination = $source . '/' . $filename;
// 打开压缩文件并设置模式为创建新文件
if ($zip->open($destination, \ZipArchive::CREATE) === true) {
// 递归遍历要压缩的源文件夹中的所有文件
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file) {
// 如果当前文件不是目录,则将其添加到压缩文件中
if (!$file->isDir()) {
$filePath = $file->getRealPath(); // 获取文件的绝对路径
$relativePath = substr($filePath, strlen($source) + 1); // 计算文件相对于源文件夹的路径
// 将文件添加到压缩文件中,使用相对路径作为文件名
$zip->addFile($filePath, $relativePath);
}
}
// 关闭 ZipArchive 实例
$zip->close();
// 输出压缩文件的绝对路径
echo '压缩完成!压缩文件路径:' . $destination;
} else {
echo '压缩失败!';
}
}
网友评论