复制对象

复制对象

您可以使用 copyObject 接口复制对象,您需要设置复制的对象名,所在的桶以及目标桶和对象名:

$desBucket = '<dest-bucket-name>';   //目标桶
$desKeyName = '<dest-object-key>';   //目标对象名
$srcBucket = '<source-bucket-name>'; //从此桶复制
$srcKeyName = '<source-object-key>'; //复制的对象名
try {
    $result = $s3Client->copyObject(array(
        'Bucket' => $desBucket,
        'Key' => $desKeyName,
        'CopySource' => '/' . $srcBucket . '/' . $srcKeyName,
    ));
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

大文件分片复制

文件比较大(超过1GB)的情况下,直接使用copyObject 可能会出现超时,需要使用分片复制的方式进行文件复制。Aws\S3\MultiPartCopy封装了分片复制的接口,可以用于复制文件。

public function MultiPartCopy()
{
    $src_bucket = $this->bucket;
    $src_key = "ExampleObject.avi";

    $dst_bucket = $this->bucket;
    $dst_key = "ExampleObject1.txt";

    $source = '/'.$src_bucket.'/'.$src_key;
    $uploader = new Aws\S3\MultiPartCopy($this->s3Client, $source, [
        'bucket' => $dst_bucket,
        'key'    => $dst_key,
        'concurrency' => 5,         // 设置上传分片 UploadPart 操作的最大并行数量,默认为5.
        'part_size' => 5242880,     // 设置分片大小,默认为5M.
        'acl' => 'public-read',     // 设置ACL,参考值private | public-read
        'before_initiate' => function(\Aws\Command $command)
        {
            $command['ContentType'] = 'text/json';      // 设置content-type
        },
    ]);

    try {
        $result = $uploader->upload();
        echo "Upload complete: {$result['ObjectURL']}" . "\n";
    } catch (\Aws\Exception\MultipartUploadException $e) {
        echo $e->getMessage() . "\n";
    }
}