亚马逊云s3上传
完整封装对里面的配置进行修改即可
import {
CreateMultipartUploadCommand,
UploadPartCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand,
S3Client
} from "@aws-sdk/client-s3"
const getExtra = (str: string) => {
return str.split(".").pop()
}
export const multipartUpload = async (key: string, buffer: File, callback: Function) => {
// 对key进行重命名
key = `${parseInt(Math.random() * 10000000000 + "")}_${new Date().getTime()}.${getExtra(key)}`
const s3Client = new S3Client({
region: "cn-north-1",
credentials: {
accessKeyId: "AKIASU2SCXMQYERY4ZKV",
secretAccessKey: "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"
}
})
const bucketName = "ias-library-bucket-nonprod"
let uploadId
// 每兆上传
const chunkSize = 1 * 1024 * 1024
const sliceFile = (file: File) => {
// 默认切片大小为1MB
const chunks = Math.ceil(file.size / chunkSize)
const fileChunks = []
for (let i = 0; i < chunks; i++) {
const start = i * chunkSize
const end = start + chunkSize
// 使用 slice() 方法创建文件切片
const chunk = file.slice(start, Math.min(end, file.size))
fileChunks.push(chunk)
}
return fileChunks
}
try {
const multipartUpload = await s3Client.send(
new CreateMultipartUploadCommand({
Bucket: bucketName,
Key: key,
ACL: "public-read" // 需设置成public-read方便web访问
})
)
uploadId = multipartUpload.UploadId
// File每1MB为一块,求需要上传多少次、循环上传
const fileChunks = sliceFile(buffer)
const uploadResults = []
// Upload each part.
for (let i = 0; i < fileChunks.length; i++) {
const data = await s3Client.send(
new UploadPartCommand({
Bucket: bucketName,
Key: key,
UploadId: uploadId,
Body: fileChunks[i],
PartNumber: i + 1
})
)
callback((chunkSize * (i + 1)) / buffer.size)
uploadResults.push(data)
}
return await s3Client.send(
new CompleteMultipartUploadCommand({
Bucket: bucketName,
Key: key,
UploadId: uploadId,
MultipartUpload: {
Parts: uploadResults.map(({ ETag }, i) => ({
ETag,
PartNumber: i + 1
}))
}
})
)
// Verify the output by downloading the file from the Amazon Simple Storage Service (Amazon S3) console.
// Because the output is a 1 MB string, text editors might struggle to open the file.
} catch (err) {
console.error(err)
if (uploadId) {
const abortCommand = new AbortMultipartUploadCommand({
Bucket: bucketName,
Key: key,
UploadId: uploadId
})
await s3Client.send(abortCommand)
}
}
}
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
上次更新: 2024/08/07, 18:05:11