Подтвердить что ты не робот

Схват содержимого объекта с S3 через PHP SDK 2?

Я пытался выяснить, как захватить содержимое из ведра S3, чтобы включить в ZipArchive для клиента, который хранит файлы на S3, теперь им нужно создать отчеты, в которых хранятся файлы, которые были перенесены на S3 их клиентов. Я попробовал следующее с PHP SDK 2 API (установлен с PEAR):

require 'AWSSDKforPHP/aws.phar';

use Aws\S3\S3Client;
use Aws\Common\Enum\Region;

$config = array(
    'key'    => 'the-aws-key',
    'secret' => 'the-aws-secret',
    'region' => Region::US_EAST_1
);

$aws_s3 = S3Client::factory($config);
$app_config['s3']['bucket'] = 'the-aws-bucket';
$app_config['s3']['prefix'] = '';
$attach_name = 'hosted-test-file.jpg';
try {
    $result = $aws_s3->getObject(
        array(
            'Bucket' => $app_config['s3']['bucket'],
            'Key' => $app_config['s3']['prefix'].$attach_name
        )
    );
    var_dump($result);
    $body = $result->get('Body');
    var_dump($body);
    $handle = fopen('php://temp', 'r');
    $content = stream_get_contents($handle);
    echo "String length: ".strlen($content);
} catch(Aws\S3\Exception\S3Exception $e) {
    echo "Request failed.<br />";
}

Однако все, что он возвращает, является объектом Guzzle\Http\EntityBody, не уверен, как захватить фактическое содержимое, чтобы я мог его вставить в zip файл.

Grabbing Object

object(Guzzle\Service\Resource\Model)[126]
    protected 'structure' => object(Guzzle\Service\Description\Parameter)[109]
    protected 'name' => null
    protected 'description' => null
    protected 'type' => string 'object' (length = 6)
    protected 'required' => boolean false
    protected 'enum' => null
    protected 'additionalProperties' => boolean true
    protected 'items' => null
    protected 'parent' => null
    protected 'ref' => null
    protected 'format' => null
    protected 'data' => array (size = 11)
        'Body' => object(Guzzle\Http\EntityBody)[97]
            protected 'contentEncoding' => boolean false
            protected 'rewindFunction' => null
            protected 'stream' => resource(292, stream)
            protected 'size' => int 3078337
            protected 'cache' => array (size = 9)
            ...
        'DeleteMarker' => string '' (length = 0)
        'Expiration' => string '' (length = 0)
        'WebsiteRedirectLocation' => string '' (length = 0)
        'LastModified' => string 'Fri, 30 Nov 2012 21:07:30 GMT' (length = 29)
        'ContentType' => string 'binary/octet-stream' (length = 19)
        'ContentLength' => string '3078337' (length = 7)
        'ETag' => string '"the-etag-of-the-file"' (length = 34)
        'ServerSideEncryption' => string '' (length = 0)
        'VersionId' => string '' (length = 0)
        'RequestId' => string 'request-id' (length = 16)

Возврат из тела

object(Guzzle\Http\EntityBody)[96]
    protected 'contentEncoding' => boolean false
    protected 'rewindFunction' => null
    protected 'stream' => resource(292, stream)
    protected 'size' => int 3078337
    protected 'cache' => array (size = 9)
        'wrapper_type' => string 'php' (length = 3)
        'stream_type' => string 'temp' (length = 4)
        'mode' => string 'w+b' (length = 3)
        'unread_bytes' => int 0
        'seekable' => boolean true
        'uri' => string 'php://temp' (length = 10)
        'is_local' => boolean true
        'is_readable' => boolean true
        'is_writable' => boolean true

// Echo of strlen()
String length: 0

Любая информация будет высоко оценена, спасибо!

Решение

Мне нужно разобраться, но я смог найти суть, которая указала мне в правильном направлении, для того чтобы получить содержимое файла, вам нужно сделать следующее:

require 'AWSSDKforPHP/aws.phar';

use Aws\S3\S3Client;
use Aws\Common\Enum\Region;

$config = array(
    'key'    => 'the-aws-key',
    'secret' => 'the-aws-secret',
    'region' => Region::US_EAST_1
);

$aws_s3 = S3Client::factory($config);
$app_config['s3']['bucket'] = 'the-aws-bucket';
$app_config['s3']['prefix'] = '';
$attach_name = 'hosted-test-file.jpg';
try {
    $result = $aws_s3->getObject(
        array(
            'Bucket' => $app_config['s3']['bucket'],
            'Key' => $app_config['s3']['prefix'].$attach_name
        )
    );
    $body = $result->get('Body');
    $body->rewind();
    $content = $body->read($result['ContentLength']);
} catch(Aws\S3\Exception\S3Exception $e) {
    echo "Request failed.<br />";
}
4b9b3361

Ответ 1

Тело ответа хранится в объекте Guzzle\Http\EntityBody. Это используется для защиты вашего приложения от загрузки чрезвычайно больших файлов и нехватки памяти.

Если вам нужно использовать содержимое объекта EntityBody в виде строки, вы можете передать объект в строку:

$result = $s3Client->getObject(array(
    'Bucket' => $bucket,
    'Key'    => $key
));

// Cast as a string
$bodyAsString = (string) $result['Body'];

// or call __toString directly
$bodyAsString = $result['Body']->__toString();

Вы также можете скачать прямо в целевой файл, если необходимо:

use Guzzle\Http\EntityBody;

$s3Client->getObject(array(
  'Bucket' => $bucket,
  'Key'    => $key,
  'command.response_body' => EntityBody::factory(fopen("/tmp/{$key}", 'w+'))
));

Ответ 2

При вызове getObject вы можете передать массив параметров. В этих параметрах вы можете указать, хотите ли вы загрузить объект в свою файловую систему.

$bucket = "bucketName";
$file = "fileName";
$downloadTo = "path/to/save";

$opts = array(  // array of options
    'fileDownload' => $downloadTo . $file   // tells the SDK to download the 
                                             // file to this location
);

$result = $aws_s3->getObject($bucket, $file, $opts);

ссылка getObject

Ответ 3

Я не знаком с SDK версии 2.00, но похоже, что вы передали контекст потока на php://temp. От взгляда на ваш обновленный вопрос и краткий взгляд на документацию кажется, что поток может быть доступен как:

$result = $aws_s3->getObject(
    array(
        'Bucket' => $app_config['s3']['bucket'],
        'Key' => $app_config['s3']['prefix'].$attach_name
    )
);
$stream = $result->get('stream');
$content = file_get_contents($stream);

Ответ 4

<?php
   $o_iter = $client->getIterator('ListObjects', array(
    'Bucket' => $bucketname
   ));
   foreach ($o_iter as $o) {
    echo "{$o['Key']}\t{$o['Size']}\t{$o['LastModified']}\n";
   }