How to download a folder from s3 in laravel?

by giovanny.lueilwitz , in category: PHP Frameworks , 5 months ago

How to download a folder from s3 in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 5 months ago

@giovanny.lueilwitz 

To download a folder from an S3 bucket in Laravel, you can use the ZipArchive class to create a zip file containing all the files in the folder, and then download the zip file.


Here's an example code snippet to download a folder from an S3 bucket in Laravel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use Storage;
use ZipArchive;

public function downloadFolderFromS3($folderName)
{
    // Specify the S3 bucket name
    $bucket = 'your-s3-bucket-name';

    // Create a temporary file to store the zip archive
    $temporaryFilePath = tempnam(sys_get_temp_dir(), 'zip');
    
    $zip = new ZipArchive;
    $zip->open($temporaryFilePath, ZipArchive::CREATE);

    // Get all the files in the folder
    $files = Storage::disk('s3')->files($folderName);

    // Add each file to the zip archive
    foreach ($files as $file) {
        $fileContent = Storage::disk('s3')->get($file);
        $zip->addFromString(basename($file), $fileContent);
    }

    $zip->close();

    // Download the zip archive
    return response()->download($temporaryFilePath, 'folder.zip')->deleteFileAfterSend(true);
}


In this code snippet, replace 'your-s3-bucket-name' with the name of your S3 bucket, and call the downloadFolderFromS3($folderName) method passing the folder name as an argument to download the folder as a zip file.