Amazon S3将目录复制到另一个目录

时间:2012-09-20 18:18:59

标签: amazon-s3 directory amazon move

如何使用PHP API将包含子文件夹和文件的文件夹复制/复制到S3存储桶中的另一个目录中?

$s3->copy_object仅复制文件夹,但不复制文件和子文件夹。

我是否必须使用$s3->list_objects来获取所有文件和目录,并在每个文件/目录上运行$s3->copy_object

4 个答案:

答案 0 :(得分:0)

一种方法是使用列表对象并逐个移动每个对象。另一种方法是使用s3fuse,这将使你的s3存储桶成为本地目录,然后你可以只应用像'mv'这样的简单命令来移动文件。

答案 1 :(得分:0)

这里有一些代码来自亚马逊。此代码将项目复制三次到目标,您需要做的是更改它,以便它遍历每个键并将其添加到批处理。

<?php

// Include the AWS SDK using the Composer autoloader.
require 'vendor/autoload.php';

use Aws\S3\S3Client;

$sourceBucket = '*** Your Source Bucket Name ***';
$sourceKeyname = '*** Your Source Object Key ***';
$targetBucket = '*** Your Target Bucket Name ***';

// Instantiate the client.
$s3 = S3Client::factory();

// Copy an object.
$s3->copyObject(array(
    'Bucket'     => $targetBucket,
    'Key'        => "{$sourceKeyname}-copy",
    'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
));

// Perform a batch of CopyObject operations.
$batch = array();
for ($i = 1; $i <= 3; $i++) {
    $batch[] = $s3->getCommand('CopyObject', array(
        'Bucket'     => $targetBucket,
        'Key'        => "{$sourceKeyname}-copy-{$i}",
        'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
    ));
}
try {
    $successful = $s3->execute($batch);
    $failed = array();
} catch (\Guzzle\Service\Exception\CommandTransferException $e) {
    $successful = $e->getSuccessfulCommands();
    $failed = $e->getFailedCommands();
}

答案 2 :(得分:0)

scala的代码(在一个存储桶中的文件夹之间复制):

def copyFolders(bucketName: String, srcFolder: String, targetFolder: String): Unit = {
import scala.collection.JavaConversions._
val transferManager: TransferManager = TransferManagerBuilder.standard.build
try {

  for (file <- s3.listObjects(bucketName, s"$srcFolder/").getObjectSummaries) {
    val fileName = file.getKey.replace(s"$srcFolder/", "")
    if (!fileName.isEmpty) {
      val transferProcess: Copy = transferManager.copy(bucketName, file.getKey,
        bucketName, s"$targetFolder/$fileName")
      log.info(s"Old key = ${file.getKey}")
      log.info(s"New file Key = $targetFolder/$fileName")
      transferProcess.waitForCompletion()
    }
  }
} catch {
  case e: AmazonServiceException =>
    log.error(e.getErrorMessage, e)
    System.exit(1)
  case e: AmazonClientException =>
    log.error("Amazon client error: " + e.getMessage, e)
    System.exit(1)
  case e: InterruptedException =>
    log.error("Transfer interrupted: " + e.getMessage, e)
    System.exit(1)
}
}

用法:

copyFolders("mybucket", "somefolder/srcfolder", "somefolder/targetfolder")

答案 3 :(得分:0)

对于那些使用aws sdk寻找Java解决方案的人:

int