繁体   English   中英

使用 AWS SDK PHP 创建、压缩和下载 S3 文件夹/多个文件

[英]Create & zip & Download an S3 folder/multiple-files with AWS SDK PHP

我愿意创建一个 php 函数,在 js 中触发,它可以:

  • 从特定文件夹中检索所有 AWS S3 存储桶文件(我也可以提供每个文件的路径)
  • 创建一个包含所有 S3 文件的 Zip
  • 触发时下载 Zip (cta)

我可以使用此示例中的 getObject 方法下载单个文件但是,我找不到任何信息来下载多个文件并对其进行压缩。

我尝试了 downloadBucket 方法,但是它下载了我的项目架构中的所有文件,而不是 zip 文件。 这是我的代码:

<?php


// AWS Info + Connection
$IAM_KEY = 'XXXXX';
$IAM_SECRET = 'XXXXX';
$region = 'XXXXX';  

require '../../vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$FolderToDownload="FolderToDownload";


// Connection OK
$s3 = S3Client::factory(
    array(
        'credentials' => array(
            'key' => $IAM_KEY,
            'secret' => $IAM_SECRET
        ),
        'version' => 'latest',
        'region'  => $region
    )
);

try {

    $bucketName = 'XXXXX';
    $destination = 'NeedAZipFileNotAFolderPath';
    $options = array('debug'=>true);

    // ADD All Files into the folder: NeedAZipFileNotAFolderPath/Files1.png...Files12.png...
    $s3->downloadBucket($destination,$bucketName,$FolderToDownload,$options);
    
    // Looking for a zip file that can be downloaded
    // Can I use downloadBucket? Is there a better way to do it?
    // if needed I can create an array of all files (paths) that needs to be added to the zip file & dl


} catch (S3Exception $e) {
    echo $e->getMessage() . PHP_EOL;
    }


?>

如果有人可以提供帮助,那就太好了。 谢谢

您可以使用 ZipArchive,从前缀(存储桶的文件夹)中列出对象。 在这种情况下,我还使用“registerStreamWrapper”来获取密钥并添加到创建的 zip 文件中。

类似的东西:

<?php

require '/path/to/sdk-or-autoloader';

$s3 = Aws\S3\S3Client::factory(/* sdk config */);
$s3->registerStreamWrapper();

$zip = new ZipArchive;
$zip->open('/path/to/zip-you-are-creating.zip', ZipArchive::CREATE);

$bucket = 'your-bucket';
$prefix = 'your-prefix-folder'; // ex.: 'image/test/folder/'
$objects = $s3->getIterator('ListObjects', array(
    'Bucket' => $bucket,
    'Prefix' => $prefix
));

foreach ($objects as $object) {
    $contents = file_get_contents("s3://{$bucket}/{$object['Key']}"); // get file
    $zip->addFromString($object['Key'], $contents); // add file contents in zip
}

$zip->close();

// Download de zip file
header("Content-Description: File Transfer"); 
header("Content-Type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"/path/to/zip-you-are-creating.zip\""); 
readfile ('/path/to/zip-you-are-creating.zip');
    
?>

如果您愿意,也可以在下载后删除 zip 文件。

在大多数情况下必须工作,但我不想将文件保存在服务器中,但我看不到如何通过浏览器直接从 AWS S3 存储桶下载多个对象而不在我的服务器中保存文件。 如果有人知道,请与我们分享。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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