本SDK提供CreateMultipartUpload
,UploadPart
,CompleteMultipartUpload
,AbortMultipartUpload
这四个类共同实现分片上传,具体内容详见 官方文档 。
分片上传流程
在US3中,一个完整的分片上传分为初始化分片 -> 上传分片 -> 完成分片(中止分片)三个阶段。
参数说明
Bucket
: 文件上传后所在的存储空间Key
: 文件上传后在存储空间里的名称UploadId
: 用于关联所有分片的唯一标识符PartNumber
: 当前上传的分片编号Body
: 要上传的文件分片的内容ContentMD5
: 指定分片数据的 MD5 校验值
示例
执行该示例前请确保配置文件的正确性
以下代码段需要在上下文中运行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// 初始化客户端
try {
$s3Client = new S3Client([
'endpoint' => $endpoint,
'region' => $region,
'signature_version' => $signatureVersion,
'force_path_style' => $forcePathStyle,
'credentials' => [
'key' => $accessKey,
'secret' => $secretKey,
],
]);
echo "Client initialized successfully!" . PHP_EOL;
} catch (InvalidArgumentException $e) {
die("Failed to initialize Client: " . $e->getMessage());
}
try {
$createMultipartUploadResult = $s3Client->createMultipartUpload([
'Bucket' => $bucketName,
'Key' => $keyName,
]);
$uploadId = $createMultipartUploadResult['UploadId'];
$partSize = 8 * 1024 * 1024; // 8MB
$fileHandle = fopen($filePath, 'rb');
if (!$fileHandle) {
throw new Exception("无法打开文件: $filePath");
}
$partNumber = 1;
$parts = [];
while (!feof($fileHandle)) {
$partContent = fread($fileHandle, $partSize);
if ($partContent === false || strlen($partContent) === 0) {
break;
}
// 上传分片
$md5Hash = base64_encode(md5($partContent, true));
$uploadPartResult = $s3Client->uploadPart([
'Bucket' => $bucketName,
'Key' => $keyName,
'UploadId' => $uploadId,
'PartNumber' => $partNumber,
'Body' => $partContent,
'ContentMD5' => $md5Hash,
]);
echo "Uploaded part $partNumber successfully!" . PHP_EOL;
// 保存分片信息
$parts[] = [
'PartNumber' => $partNumber,
'ETag' => $uploadPartResult['ETag'],
];
$partNumber++;
// 释放内存
unset($partContent);
gc_collect_cycles();
}
fclose($fileHandle);
// 完成上传
$s3Client->completeMultipartUpload([
'Bucket' => $bucketName,
'Key' => $keyName,
'UploadId' => $uploadId,
'MultipartUpload' => ['Parts' => $parts],
]);
echo "File uploaded successfully!" . PHP_EOL;
} catch (AwsException $e) {
echo "Error uploading file: " . $e->getMessage() . PHP_EOL;
if (isset($uploadId)) {
$s3Client->abortMultipartUpload([
'Bucket' => $bucketName,
'Key' => $keyName,
'UploadId' => $uploadId,
]);
echo "Aborted multipart upload." . PHP_EOL;
}
} catch (Exception $e) {
echo "错误: " . $e->getMessage() . PHP_EOL;
}