تاریخ امروز:30 فروردین 1403
ساخت فایل zip در لاراول و دانلود فایل

ساخت فایل Zip در لاراول و دانلود فایل

در این آموزش می‌خوام یک روش ساده رو برای ساخت فایل Zip در لاراول خدمتتون بدم. برای این منظور من از کلاس ZipArchive استفاده کردم.برای استفاده از این کلاس باید ext-zip در php.ini روشن باشه.

خب مثال اول این هستش که من به طور مثال فایل موجود در آدرس storage/invoices/aaa001.pdf رو می‌خوام زیپ و دانلود کنم:

$zip_file = 'invoices.zip'; // Name of our archive to download

// Initializing PHP class
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

$invoice_file = 'invoices/aaa001.pdf';

// Adding file: second parameter is what will the path inside of the archive
// So it will create another folder called "storage/" inside ZIP, and put the file there.
$zip->addFile(storage_path($invoice_file), $invoice_file);
$zip->close();

// We return the file immediately after download
return response()->download($zip_file);

به همین سادگی.

حالا فرض کنید می‌خوایم فولدر storage/invoices رو به طور کامل زیپ و دانلود کنیم:

$zip_file = 'invoices.zip';
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

$path = storage_path('invoices');
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($files as $name => $file)
{
    // We're skipping all subfolders
    if (!$file->isDir()) {
        $filePath     = $file->getRealPath();

        // extracting filename with substr/strlen
        $relativePath = 'invoices/' . substr($filePath, strlen($path) + 1);

        $zip->addFile($filePath, $relativePath);
    }
}
$zip->close();
return response()->download($zip_file);

به همین سادگی

 

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *