Delete object or bucket in Amazon S3?

北城余情 提交于 2019-12-08 16:39:14

问题


I created a new amazon bucket called "photos". The bucket url is something like:

www.amazons3.salcaiser.com/photos

Now I upload subfolders containing files, into that bucket for example

www.amazons3.salcaiser.com/photos/thumbs/file.jpg

My questions are, does thumbs/ is assumed a new bucket or is it an object?

Then if I want to delete the entire thumbs/ directory need I first to delete all files inside that or can I delete all in one time?


回答1:


In the case you are describing, "photos" is the bucket. S3 does not have sub-buckets or directories. Directories are simulated by using slashes in the object key. "thumbs/file.jpg" is an object key and "thumbs/" would be considered a key prefix.

Dagon's examples are good and use the older version 1.x of the AWS SDK for PHP. However, you can do this more easily with the newest 2.4.x version AWS SDK for PHP which includes a helper method for deleting multiple objects.

<?php

// Include the SDK. This line depends on your installation method.
require 'aws.phar';

use Aws\S3\S3Client;

$s3 = S3Client::factory(array(
    'key'    => 'your-aws-access-key',
    'secret' => 'your-aws-secret-key',
));

// Delete the objects in the "photos" bucket with the a prefix of "thumbs/"
$s3->deleteMatchingObjects('photos', 'thumbs/');



回答2:


//Include s3.php file first in code

if (!class_exists('S3'))
            require_once('S3.php');
        //AWS access info
        if (!defined('awsAccessKey'))
            define('awsAccessKey', 'awsAccessKey');
        if (!defined('awsSecretKey'))
            define('awsSecretKey', 'awsSecretKey');
        //instantiate the class
        $s3 = new S3(awsAccessKey, awsSecretKey);

  if ($s3->deleteObject("bucketname", `filename`)) {
        echo 'deleted';
}
else
{
echo 'no file found';
}



回答3:


found some code snippets for 'directory' deletion - i did not write them:

PHP 5.3+:

$s3 = new AmazonS3();

$bucket = 'your-bucket';
$folder = 'folder/sub-folder/';

$s3->get_object_list($bucket, array(
    'prefix' => $folder
))->each(function($node, $i, $s3) {
    $s3->batch()->delete_object($bucket, $node);
}, array($s3));
$responses = $s3->batch()->send();

var_dump($responses->areOK());

Older PHP 5.2.x:

$s3 = new AmazonS3();


$bucket = 'your-bucket';
$folder = 'folder/sub-folder/';

$s3->get_object_list($bucket, array(
    'prefix' => $folder
))->each('construct_batch_delete', array($s3));

function construct_batch_delete($node, $i, &$s3)
{
    $s3->batch()->delete_object($bucket, $node);
}

$responses = $s3->batch()->send();

var_dump($responses->areOK());


来源:https://stackoverflow.com/questions/18346308/delete-object-or-bucket-in-amazon-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!