簡體   English   中英

如何在不使用 php 壓縮的情況下下載文件夾及其所有文件夾和文件

[英]How to download a folder with all its folders and files without zipping it with php

1 - 我有一個文件夾,里面有很多用戶文件夾,每個用戶的文件夾里面都有其他文件夾,里面有這樣的圖像:

  • localhost/cm/app/model/uploads/mark/3/small/car.jpg
  • localhost/cm/app/model/uploads/mark/3/big/car.jpg
  • localhost/cm/app/model/uploads/stiven/9/small/pc.jpg
  • localhost/cm/app/model/uploads/stiven/9/big/pc.jpg

2 - 我希望我下載這個文件夾及其所有內容。

3 - 我更喜歡下載它而不用相同的名稱壓縮它,如果用任何名稱壓縮它是不可能的。

4 - 我使用了此代碼,但它不起作用,因為當我在下載 zip 文件夾后嘗試打開它時,會出現一條錯誤消息並告訴我“存檔格式未知或已損壞”,這是我的代碼:

<?php
$dir = 'http://localhost/cm/app/model/uploads'; //folder path

$archive = time().'download.zip';

$zip = new ZipArchive;
$zip->open($archive, ZipArchive::CREATE);
$files = scandir($dir);
unset($files[0], $files[1]);
foreach ($files as $file) {
$zip->addFile($dir.'/'.$file);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>

*那么如何在不壓縮的情況下下載我的文件夾及其所有文件夾和圖像?

我懷疑你的代碼有錯誤。 也許 ext-zip 沒有安裝 檢查這一點的一種方法是在終端中運行php -m ,它將顯示所有安裝和啟用的模塊。

如果您使用文本編輯器打開 zip 文件,就會出現錯誤消息而不是存檔數據。

這是我發現的最好方法:

 <?php
 // Get real path for our folder
 $rootPath = realpath('folder_for_ziping');

 // Initialize archive object
 $zip = new ZipArchive();
 $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
 $files = new RecursiveIteratorIterator(
 new RecursiveDirectoryIterator($rootPath),
 RecursiveIteratorIterator::LEAVES_ONLY
);

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);

    // Add current file to archive
    $zip->addFile($filePath, $relativePath);
  }
}

// Zip archive will be created only after closing object
$zip->close();
$archive = "file.zip";
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM