CODE VN

Tạo một tệp Zip và tải xuống trong Laravel với ví dụ

Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách tạo một tệp zip và tải xuống trong Laravel. chúng ta sẽ sử dụng lớp ZipArchive đã có từ PHP 5.2. Để sử dụng nó, hãy xác nhận rằng tiện ích mở rộng ext-zip đã được bật trong php.ini của bạn .

Mã ví dụ:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ZipController extends Controller
{
    public function downloadZip(Request $request){
        $zip_file = 'invoices.zip';

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

        $invoice_file = 'invoices/AMZ-001.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);
    }
}

Mã hóa vui vẻ !!!

1.00 GEEK