分片上传

分片上传步骤较多,包括初始化、文件切片、各个分片上传、完成上传。为了简化分片上传,可以使用TransferManager接口进行分片上传。

bool S3Demo::TranferUpload()
{
  const Aws::String object_name = "ExampleObject.txt";
  const Aws::String local_path = "E:/ExampleObject.txt";

  std::shared_ptr<Aws::Utils::Threading::PooledThreadExecutor> executor = 
    Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>("executor", 25);
  Aws::Transfer::TransferManagerConfiguration transferConfig(executor.get());
  transferConfig.s3Client = s3_client;
  // 默认分片大小5MB
  // transferConfig.bufferSize = Aws::Transfer::MB5; 
  // 设置公共读
  // transferConfig.putObjectTemplate.SetACL(Aws::S3::Model::ObjectCannedACL::public_read);
  // transferConfig.createMultipartUploadTemplate.SetACL(Aws::S3::Model::ObjectCannedACL::public_read);

  std::shared_ptr<Aws::Transfer::TransferHandle> requestPtr(nullptr);

  transferConfig.downloadProgressCallback =
    [](const Aws::Transfer::TransferManager*, const std::shared_ptr<const Aws::Transfer::TransferHandle>& handle)
  {
    std::cout << "\r" << "<AWS UPLOAD> Upload Progress: " <<
      static_cast<int>(handle->GetBytesTransferred() * 100.0 / handle->GetBytesTotalSize()) << " Percent " <<
      handle->GetBytesTransferred() << " bytes\n";
  };

  std::shared_ptr<Aws::Transfer::TransferManager> transferManager =
    Aws::Transfer::TransferManager::Create(transferConfig);

  Aws::String contentType = "binary/octet-stream";
  Aws::Map<Aws::String, Aws::String> metadata;
  requestPtr = transferManager->UploadFile(local_path, s3_bucket_name,
    object_name, contentType, metadata);
  requestPtr->WaitUntilFinished();

  // Check status
  if (requestPtr->GetStatus() == Aws::Transfer::TransferStatus::COMPLETED) {
    if (requestPtr->GetBytesTotalSize() == requestPtr->GetBytesTransferred()) {
      std::cout << "success" << std::endl;
    }
    else {
      std::cout << "failed" << std::endl;
    }
  }
  else {
    std::cout << "failed" << std::endl;
  }
  return true;
}

参数如下:

参数 意义 类型
local_path 要上传的本地文件 string
bucket_name 桶名 string
object_name 对象名 string
contentType http contentType头 string
metadata 对象自定义元数据 map<string, string>

注意:acl在TransferManagerConfiguration中设置