简体   繁体   中英

Proper way to download multiple files from s3 on fly in zip?

I want to download multiple files from amazon s3 in zip file while click on single download button.

I want to achieve this using php or JavaScript.

I went over many solutions such as: Use recursive in aws cli, Zipstream on fly, but I didn't get any proper solution.

Do you have any idea for another, more efficient solution?

<?php

$urls = [
    'http://django-dev.s3.amazonaws.com/static/img/sample-store.jpg',
    'http://ds-assets.s3.amazonaws.com/baobao/feature/2020/video/movie_sample.mp4',
    'http://ds-assets.s3.amazonaws.com/briefing/mailmagazine/2019/0701/sample_g.jpg',
];

$mh = curl_multi_init();
$resources = [];

foreach ($urls as $key => $url) {
    $resources[$key]['fp'] = fopen(sys_get_temp_dir() . '/file' . $key, 'w+'); // file pointer
    $resources[$key]['ch'] = curl_init($url); // curl handle
    curl_setopt($resources[$key]['ch'], CURLOPT_FILE, $resources[$key]['fp']); 
    curl_setopt($resources[$key]['ch'], CURLOPT_FOLLOWLOCATION, true);
    curl_multi_add_handle($mh, $resources[$key]['ch']);
}

$running = null;
do {
    curl_multi_exec($mh, $running);
} while ($running);

$zip = new ZipArchive();
$zip->open(sys_get_temp_dir() . '/files.zip', ZIPARCHIVE::CREATE);

foreach ($resources as $key => $resource) {
    curl_multi_remove_handle($mh, $resource['ch']);
    curl_close($resource['ch']);
    fclose($resource['fp']);
    $zip->addFile(sys_get_temp_dir() . '/file' . $key, '/file' . $key);
}

curl_multi_close($mh);
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=files.zip');
header('Pragma: no-cache');
readfile(sys_get_temp_dir() . '/files.zip');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM