Rom*_*ain 4 php zip amazon-s3 amazon-web-services
我愿意创建一个 php 函数,在 js 中触发,它可以:
我可以使用本示例中的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;
}
?>
Run Code Online (Sandbox Code Playgroud)
如果有人可以提供帮助,那就太好了。谢谢
小智 6
您可以使用 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');
?>
Run Code Online (Sandbox Code Playgroud)
如果您愿意,也可以在下载后删除 zip 文件。
在大多数情况下必须有效,但我不想将文件保存在服务器中,但我不知道如何通过浏览器直接从 AWS S3 存储桶下载多个对象,而不在服务器中保存文件。如果有人知道,请与我们分享。
| 归档时间: |
|
| 查看次数: |
10121 次 |
| 最近记录: |