在开始之前,您必须生成 Access Key。所有示例都将使用 access_key_id 和 access_key_secret 变量,分别代表您生成的 Access Key ID(访问密钥 ID) 和 Secret Access Key(秘密访问密钥) 值。
如果您对较新版本的 AWS JavaScript SDK 感兴趣,请访问此专用的 aws-sdk-js-v3 示例页面。
JavaScript 或 TypeScript 用户可以继续照常使用 aws-sdk ↗ npm 包。实例化 S3 服务客户端时,必须传入 R2 配置凭据:
import S3 from "aws-sdk/clients/s3.js";
const s3 = new S3({
// Provide your Cloudflare account ID
endpoint: `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`,
// Retrieve your S3 API credentials for your R2 bucket via API tokens (see: https://developers.cloudflare.com/r2/api/tokens)
accessKeyId: `${ACCESS_KEY_ID}`,
secretAccessKey: `${SECRET_ACCESS_KEY}`,
signatureVersion: "v4",
});
console.log(await s3.listBuckets().promise());
//=> {
//=> Buckets: [
//=> { Name: 'user-uploads', CreationDate: 2022-04-13T21:23:47.102Z },
//=> { Name: 'my-bucket', CreationDate: 2022-05-07T02:46:49.218Z }
//=> ],
//=> Owner: {
//=> DisplayName: '...',
//=> ID: '...'
//=> }
//=> }
console.log(await s3.listObjects({ Bucket: "my-bucket" }).promise());
//=> {
//=> IsTruncated: false,
//=> Name: 'my-bucket',
//=> CommonPrefixes: [],
//=> MaxKeys: 1000,
//=> Contents: [
//=> {
//=> Key: 'cat.png',
//=> LastModified: 2022-05-07T02:50:45.616Z,
//=> ETag: '"c4da329b38467509049e615c11b0c48a"',
//=> ChecksumAlgorithm: [],
//=> Size: 751832,
//=> Owner: [Object]
//=> },
//=> {
//=> Key: 'todos.txt',
//=> LastModified: 2022-05-07T21:37:17.150Z,
//=> ETag: '"29d911f495d1ba7cb3a4d7d15e63236a"',
//=> ChecksumAlgorithm: [],
//=> Size: 279,
//=> Owner: [Object]
//=> }
//=> ]
//=> }您还可以生成预签名链接,以便临时共享存储桶的公开读取或写入访问权限。
// Use the expires property to determine how long the presigned link is valid.
console.log(
await s3.getSignedUrlPromise("getObject", {
Bucket: "my-bucket",
Key: "dog.png",
Expires: 3600,
}),
);
// You can also create links for operations such as putObject to allow temporary write access to a specific key.
// Specify ContentType to restrict uploads to a specific file type.
console.log(
await s3.getSignedUrlPromise("putObject", {
Bucket: "my-bucket",
Key: "dog.png",
Expires: 3600,
ContentType: "image/png",
}),
);https://my-bucket.<ACCOUNT_ID>.r2.cloudflarestorage.com/dog.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-Date=<timestamp>&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature>
https://my-bucket.<ACCOUNT_ID>.r2.cloudflarestorage.com/dog.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-Date=<timestamp>&X-Amz-Expires=3600&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=<signature>您可以使用 putObject 示例生成的链接,在预签名链接过期之前向指定的存储桶和键上传对象。使用带有 ContentType 的预签名 URL 时,客户端必须包含匹配的 Content-Type 请求头。
curl -X PUT "https://my-bucket.<ACCOUNT_ID>.r2.cloudflarestorage.com/dog.png?X-Amz-Algorithm=..." \
-H "Content-Type: image/png" \
--data-binary @dog.png生成用于上传的预签名 URL 时,您可以通过以下方式限制滥用和误用:
-
限制 Content-Type:在预签名 URL 参数中指定允许的内容类型。如果客户端发送不同的
Content-Type请求头,上传将失败。 -
配置 CORS:在存储桶上设置 CORS 规则,以控制哪些源可以上传文件。通过 Cloudflare 仪表板 ↗ 向存储桶设置添加 JSON 策略来配置 CORS:
[
{
"AllowedOrigins": ["https://example.com"],
"AllowedMethods": ["PUT"],
"AllowedHeaders": ["Content-Type"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 3600
}
]然后生成带有 Content-Type 限制的预签名 URL:
const putUrl = await s3.getSignedUrlPromise("putObject", {
Bucket: "my-bucket",
Key: "user-upload.png",
Expires: 3600,
ContentType: "image/png",
});客户端使用此预签名 URL 时必须:
- 从允许的源发起请求(由 CORS 强制执行)
- 包含
Content-Type: image/png请求头(由签名强制执行)