【发布时间】:2021-07-06 20:00:19
【问题描述】:
我无法使用 aws4fetch 调用 AWS Api。
谁能给我一个关于如何使用 cloudflare workers 调用 S3 putobject 的例子?
【问题讨论】:
标签: amazon-s3 aws-sdk aws-sdk-js cloudflare-workers
我无法使用 aws4fetch 调用 AWS Api。
谁能给我一个关于如何使用 cloudflare workers 调用 S3 putobject 的例子?
【问题讨论】:
标签: amazon-s3 aws-sdk aws-sdk-js cloudflare-workers
下面的代码对我有用,可以将一个简单的 txt 文件从 cloudflare worker 上传到 amazon S3 存储桶
导入 aws4fetch
const aws4fetch = require('aws4fetch')
声明您在 aws 中创建具有至少 putobject 和编程访问权限的 iam 配置文件时保存的访问密钥和秘密(通过仅将您感兴趣的 arn 存储桶作为资源传递来保护它)
const access_key = '<access_key_id_here>';
const access_secret = '<access_secret_here>';
const region = '<region>';
const bucket = '<bucket_name>';
初始化 aws4fetch 客户端
const aws = new aws4fetch.AwsClient({
accessKeyId:access_key,
secretAccessKey:access_secret
});
const endpoint = 'https://'+bucket+'.s3.'+region+'.amazonaws.com/';
addEventListener('fetch', function(event) {
event.respondWith(handleRequest(event.request))
});
async function handleRequest(request) {
const filename_key = 'test.txt';
const content = `the content of the file`;
const res = await aws.fetch(endpoint+filename_key,
{ body: content, method: 'PUT'})
return new Response('ok')
}
请注意,您也可以使用 aws-sdk,这样可以更轻松地与 aws s3 进行交互,但它会花费您至少 350kbytes 的额外代码(有 1mbyte 工作脚本的限制)
【讨论】: