本SDK提供DeleteObjectsCommand
类和HeadObjectCommand
类实现文件删除。完整代码详见 Github 。
DeleteObjectsCommand
调用的 S3 API 为 DeleteObjects, 具体参见DeleteObjects API 文档。
HeadObjectCommand
调用的 S3 API 为 HeadObject, 具体参见HeadObject API 文档。
参数说明
Bucket
: 文件所在的存储空间Key
: 文件在存储空间内的名称
示例
执行该示例前请确保配置文件的正确性
以下代码段需要在上下文中运行
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
function DeleteObjects() {
const [bucketName, setBucketName] = useState("");
const [objectKeys, setObjectKeys] = useState("");
const [deleteStatus, setDeleteStatus] = useState("");
const checkObjectExists = async (key) => {
try {
await s3.send(new HeadObjectCommand({ Bucket: bucketName, Key: key }));
return true;
} catch (err) {
if (err.name === 'NotFound') {
return false;
} else {
throw err;
}
}
};
const handleDelete = async () => {
const keysArray = objectKeys.split(",").map(key => key.trim());
try {
const existingKeys = [];
for (const key of keysArray) {
const exists = await checkObjectExists(key);
if (exists) {
existingKeys.push({ Key: key });
}
}
if (existingKeys.length === 0) {
setDeleteStatus("没有找到可删除的对象");
return;
}
const deleteParams = {
Bucket: bucketName,
Delete: {
Objects: existingKeys,
},
};
const command = new DeleteObjectsCommand(deleteParams);
const response = await s3.send(command);
setDeleteStatus(`成功删除 ${response.Deleted.length} 个对象. 删除对象: ${response.Deleted.map(d => d.Key).join(", ")}`);
} catch (err) {
console.error("删除文件失败:", err);
setDeleteStatus("删除对象失败");
}
};