从zip中快速下载s3的多个文件的正确方法?

时间:2018-01-02 17:48:20

标签: javascript php amazon-s3 zipfile

我想在zip文件中下载亚马逊s3的多个文件,同时点击单个下载按钮。

我想用php或JavaScript实现这个目标。

我经历了许多解决方案,例如:在aws cli中使用递归, Zipstream飞行,但我没有得到任何适当的解决方案。

您对另一种更有效的解决方案有什么想法吗?

1 个答案:

答案 0 :(得分:0)

<?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');
相关问题