I’m struggling to rename a file within the same bucket with Amazon S3 SDK. I am referring to copy object in the API docs.
Here is my call, but it keeps returning “specified bucket does not exist”.
$clients = S3Client::factory(array(
'key' => 'key',
'secret' => 'secret'
));
try {
$result = $clients->copyObject(array(
'ACL' => 'private',
// Bucket is required
'Bucket' => 'david1982.audio',
// CopySource is required
'CopySource' => 'mp3/music.mp3',
// Key is required
'Key' => 'mp3/music_name_updated.mp3',
'MetadataDirective' => 'REPLACE'
));
echo json_encode($result);
} catch (Exception $e) {
echo json_encode($e->getMessage());
}
Before someone points out the obvious and asks “Does your bucket exist?’ yes, it definitely exists. I can run a call with the same keys and get all my files from that bucket.
I really want to be able to rename a file via the API. You can do it within the Amazon S3 Browser.
For some reason, you have to include the bucket in CopySource
.
$result = $clients->copyObject(array(
'ACL' => 'private',
// Bucket is required
'Bucket' => 'david1982.audio',
// CopySource is required
'CopySource' => 'david1982.audio/mp3/music.mp3',
// Key is required
'Key' => 'mp3/music_name_updated.mp3',
'MetadataDirective' => 'REPLACE'
));
Yes, to copy an object you have to specify the bucket name of the object to copy.
Below an example from the official documentation: http://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingPHP.html)
use Aws\S3\S3Client;
$sourceBucket = '*** Your Source Bucket Name ***';
$sourceKeyname = '*** Your Source Object Key ***';
$targetBucket = '*** Your Target Bucket Name ***';
$targetKeyname = '*** Your Target Key Name ***';
// Instantiate the client.
$s3 = S3Client::factory();
// Copy an object.
$s3->copyObject(array(
'Bucket' => $targetBucket,
'Key' => $targetKeyname,
'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
));
After you copied the object, you'll have to delete the old one, here's an example:
$result = $client->deleteObject(array(
'Bucket' => 'string',
'Key' => 'string'
));
If anybody ends up here looking for the best way of how to do this nowadays in PHP, you can rename s3 files like this:
$s3sdk = new Sdk($awsConfig);
$s3 = $s3sdk->createS3();
$s3->registerStreamWrapper();
rename($oldName, $newName);
both names need to contain the full s3 path e.g:
"s3://yourBucketName/path/to/file"
Basically registerStreamWrapper()
enables PHP filesystem commands for s3 files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With