为何Cloudflare R2对象的Key中包含桶名称?
解决Cloudflare R2对象Key带桶名的问题
我在无服务器函数中用Cloudflare R2搭配@aws-sdk/client-s3,尝试往名为my-bucket的桶里上传对象,代码如下:
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; const s3Client = new S3Client({ region: "auto", endpoint: R2_URL, credentials: { accessKeyId: R2_ACCESS_KEY_ID, secretAccessKey: R2_SECRET_ACCESS_KEY, }, }); const putObject = new PutObjectCommand({ Bucket: "my-bucket", Key: "test.png", Body: outputBuffer, ContentType: "image/png", }); s3Client.send(putObjectCommand);
结果在Cloudflare R2控制台里看到,对象的Key变成了my-bucket/test.png,但我想要的只是test.png。怎么才能让对象用我指定的Key创建?
问题根源在你配置的endpoint参数上:
如果你的R2_URL里已经包含了桶名(比如格式是https://<你的账号ID>.r2.cloudflarestorage.com/my-bucket),再在PutObjectCommand里指定Bucket字段,就会导致桶名被重复拼到Key里。
给你两种解决办法:
办法一:修改endpoint,去掉桶名
把endpoint改成R2的通用端点,格式为https://<你的账号ID>.r2.cloudflarestorage.com,代码里保留Bucket: "my-bucket"的配置。这样SDK就能正确区分桶名和对象Key了。办法二:删除PutObjectCommand里的Bucket字段
如果你的R2_URL已经包含桶名,那PutObjectCommand里就不用再设Bucket参数,只保留Key等其他字段就行。修改后的命令代码如下:const putObject = new PutObjectCommand({ Key: "test.png", Body: outputBuffer, ContentType: "image/png", });
内容的提问来源于stack exchange,提问作者12th
相关产品推荐
相关产品推荐

