

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 文件操作

S3 传输管理器提供了上传和下载单个文件的方法。

## 上传本地文件
<a name="upload-files"></a>

要将文件上传到 Amazon S3，请使用`upload`{{<add link>}}方法。

```php
<?php

use Aws\S3\S3Transfer\Models\UploadRequest;
use Aws\S3\S3Transfer\S3TransferManager;

require __DIR__ . '/../vendor/autoload.php';

$transferManager = new S3TransferManager(null, [
    'default_region' => 'us-west-2'
]);

// Source can be from a local path to a file.
$source = '/path/to/local/file.txt';
// Or the source can be an instance of StreamInterface.
$source = GuzzleHttp\Psr7\Utils::streamFor('Hello World!');

$uploadPromise = $transferManager->upload(
    new UploadRequest(
        $source,
        [
            'Bucket' => 'amzn-s3-demo-bucket',
            'Key'    => 'path/to/s3/file.txt',
            // Additional `putObject` parameters as needed.
        ],
        [
            // Optional configuration overrides.
            'multipart_upload_threshold_bytes' => 100 * 1024 * 1024, // 100MB
            'target_part_size_bytes'           => 10 * 1024 * 1024, // 10MB
            'track_progress'                   => true,
            'request_checksum_calculation'     => 'when_required',
        ]
    )
);

// The upload is asynchronous, you can wait for it to complete.
$result = $uploadPromise->wait();

// Or you can use the promise for more complex workflows.
$result = $uploadPromise->then(
    function ($result) {
        echo "Upload succeeded!";
    },
    function ($error) {
        echo "Upload failed: " . $error->getMessage();
    }
)->wait();
```

### `upload` 方法参数
<a name="upload-parameters"></a>

该`upload`方法接受的实例`UploadRequest`{{<add link>}}作为参数。

#### `UploadRequest` 参数
<a name="upload-request-parameters"></a>


| 参数 | Type | 必需 | 说明 | 
| --- | --- | --- | --- | 
| `$source` | 字符串\| `StreamInterface` | 是 | 包含要上传的数据的本地文件路径或流的路径。 | 
| `$uploadRequestArgs` | array | 是 | 上传请求参数（必须包含存储桶和密钥）。 | 
| `$config` | array | 否 | 特定于此上传的配置替换。有关配置选项的更多信息，请参阅[以下部分](#upload-request-config-parameters)。 | 
| `$listeners` | array | 否 | 用于监视此上传的`TransferListener`对象数组。 | 
| `$progressTracker` | TransferListener | 否 | 此次上传的进度跟踪器。 | 

##### `$config`的选项 `UploadRequest`
<a name="upload-request-config-parameters"></a>

SDK 解析 S3 传输管理器[配置](configuration.md#configuration-options)中的默认`$config`值。


| Option | Type | 必需 | 说明 | 
| --- | --- | --- | --- | 
| `multipart_upload_threshold_bytes` | int | 否 | 覆盖触发分段上传时的默认阈值。 | 
| `target_part_size_bytes` | int | 否 | 覆盖默认的目标段大小（以字节为单位）。 | 
| `track_progress` | 布尔 | 否 | 覆盖默认选项以启用进度跟踪。如果此选项是，true而您未提供progressTracker参数，则 SDK 将使用默认实现。 | 
| `concurrency` | int | 否 | 覆盖并发的默认值。 | 
| `request_checksum_calculation` | 字符串 | 否 | 覆盖是否必须执行请求校验和计算的默认值。 | 

当该`upload`方法成功运行时，它将返回`UploadResult`{{<add link>}}。

## 下载 S3 对象
<a name="download-files"></a>

要从 Amazon S3 下载对象，请使用`download`{{<add link>}}方法。

```php
<?php

use Aws\S3\S3Transfer\Models\DownloadRequest;
use Aws\S3\S3Transfer\S3TransferManager;

require __DIR__ . '/../vendor/autoload.php';

$transferManager = new S3TransferManager(null, [
    'default_region' => 'us-west-2'
]);

// Download using an S3 URI.
$downloadPromise = $transferManager->download(
    new DownloadRequest(
        's3://amzn-s3-demo-bucket/path/to/s3/file.txt',
        [
            // Additional `getObject` parameters as needed.
        ],
        [
            // Optional configuration overrides.
            'response_checksum_validation' => 'when_required',
            'track_progress'               => true,
            'target_part_size_bytes'       => 10 * 1024 * 1024, // 10MB
        ]
    )
);

// Wait for the download to complete.
$result = $downloadPromise->wait();

// The SDK uses a stream-based download handler by default.
$stream = $result->getDownloadDataResult();

// You can either get the content.
$content = $stream->getContents();

// Or write the stream to a file.
file_put_contents('/path/to/local/file.txt', $stream);

// Don't forget to close the stream.
$stream->close();
```

### `download` 方法参数
<a name="download-parameters"></a>

该`download`方法接受的实例`DownloadRequest`{{<add link>}}作为参数。

#### DownloadRequest 参数
<a name="download-request-parameters"></a>


| 参数 | Type | 必需 | 说明 | 
| --- | --- | --- | --- | 
| `$source` | 字符串\|数组\| `null` | 否 | 要从 S3 下载的对象。您可以将此参数作为 S3 URI 字符串 (” s3://amzn-s3-demo-bucket/key “)、包含存储桶和密钥密钥的数组或`null`。当此值为时`null`，在`$downloadRequestArgs`参数中传递存储桶和密钥值。 | 
| `$downloadRequestArgs` | array | 否 | 其他下载对象请求参数。如果`$source`是`null`，请在此处提供存储桶和密钥值。 | 
| `$config` | array | 否 | 此下载专用的配置替换。有关配置选项的更多信息，请参阅[以下部分](#download-request-config-parameters)。 | 
| $downloadHandler | `AbstractDownloadHandler`{{<add link>}}\|`null` | 否 | 接收每个对象块并管理其下载的处理程序。<br />该`download`方法的默认处理程序使用基于流的处理程序。此处理程序将每个对象块推送到一个流中。<br />该`downloadFile`方法的默认处理程序（参见[将 S3 对象下载到本地文件](#download-file-to-local)）使用基于文件的处理程序。该处理程序将每个区块写入一个文件。<br />您可以自己实现`DownloadHandler`，以自定义 SDK 存储下载数据的位置和方式。例如，您可以将数据存储在数据库、云存储或自定义处理管道中，而不是文件或流中。 | 
| `$progressTracker` | `TransferListener` | 否 | 此下载的进度跟踪器。 | 
| `$listeners` | `array` | 否 | 用于监视此下载的`AbstractTransferListener`对象数组。 | 

##### `$config`的选项 `DownloadRequest`
<a name="download-request-config-parameters"></a>

SDK 解析 S3 传输管理器[配置](configuration.md#configuration-options)中的默认`$config`值。


| Option | Type | 必需 | 描述 | 
| --- | --- | --- | --- | 
| `multipart_download_type` | 字符串 | 否 | 覆盖默认的分段下载类型。有效值为 “部分”、“远程” | 
| `response_checksum_validation` | 字符串 | 否 | 覆盖传输管理器配置中的解析值，以确定是否应进行校验和验证。只有在中不存在此选项`ChecksumMode`时，SDK 才会`$getObjectRequestArgs`考虑使用此选项`DownloadRequest`。 | 
| `track_progress` | 布尔 | 否 | 覆盖启用进度跟踪的默认选项。如果此选项是，`true`而您没有提供`progressTracker`参数，则 SDK `DownloadRequest,` 将使用默认实现。<br />当`$progressTracker`参数为时，使用此选项启用默认进度跟踪器`null`。 | 
| `target_part_size_bytes` | int | 否 | 在范围分段下载中使用的分段大小（以字节为单位）。如果您未提供此参数，则下载将使用传输管理器上`target_part_size_bytes`配置的。 | 

当该`download`方法成功运行时，它将返回`DownloadResult`{{<add link>}}。

## 将 S3 对象下载到本地文件
<a name="download-file-to-local"></a>

要将 S3 对象直接下载到本地文件，请使用以下`downloadFile`方法：

```php
<?php

use Aws\S3\S3Transfer\Models\DownloadFileRequest;
use Aws\S3\S3Transfer\Models\DownloadRequest;
use Aws\S3\S3Transfer\S3TransferManager;

require __DIR__ . '/../vendor/autoload.php';

$transferManager = new S3TransferManager(null, [
    'default_region' => 'us-west-2'
]);

$downloadFilePromise = $transferManager->downloadFile(
    new DownloadFileRequest(
        '/path/to/local/file.txt',  // Destination file path.
        false,  // Fail when destination exists.
        new DownloadRequest(
            's3://amzn-s3-demo-bucket/path/to/s3/file.txt',
            [],  // `getObject` request args
            [
                'track_progress'         => true,
                'target_part_size_bytes' => 10 * 1024 * 1024, // 10MB parts
            ]
        )
    )
);

// Wait for download to complete.
$result = $downloadFilePromise->wait();

// `getDownloadDataResult()` returns the string for the file path of the downloaded content because
//  the default `DownloadHandler` used by `downloadFile()` is a file-based handler.
echo "File downloaded successfully at {$result->getDownloadDataResult()}!\n";
```

### `downloadFile` 方法参数
<a name="download-file-request"></a>

该`downloadFile`方法接受的实例`DownloadFileRequest`作为参数。

#### `DownloadFileRequest` 参数
<a name="download-file-request-params"></a>


| Option | Type | 必需 | 描述 | 
| --- | --- | --- | --- | 
| `$destination` | 字符串 | 是 | 保存文件的本地路径。 | 
| `$failsWhenDestinationExists` | 布尔 | 是 | 如果目标文件已经存在，则是否失败。如果此选项为`false`且目标文件存在，则 SDK 会删除或覆盖现有文件。 | 
| `$downloadRequest` | `DownloadRequest` | 是 | 配置的`DownloadRequest`对象。有关更多信息，请参阅[`DownloadRequest`对象](#download-request-parameters)。 | 

当该`downloadFile`方法成功运行时，它将返回`DownloadResult`{{<add link>}}。