Created
November 11, 2022 08:25
-
-
Save SiZapPaaiGwat/e42779358e4577f7b3a3fc90f3ab0b44 to your computer and use it in GitHub Desktop.
Save any images to Cloudflare Images with Cloudflare Worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Welcome to Cloudflare Workers! This is your first worker. | |
* | |
* - Run `wrangler dev src/index.ts` in your terminal to start a development server | |
* - Open a browser tab at http://localhost:8787/ to see your worker in action | |
* - Run `wrangler publish src/index.ts --name my-worker` to publish your worker | |
* | |
* Learn more at https://developers.cloudflare.com/workers/ | |
*/ | |
export interface Env { | |
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/ | |
// MY_KV_NAMESPACE: KVNamespace; | |
// | |
// Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/ | |
// MY_DURABLE_OBJECT: DurableObjectNamespace; | |
// | |
// Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/ | |
// MY_BUCKET: R2Bucket; | |
} | |
export default { | |
/** | |
* Upload to R2 | |
*/ | |
// async fetch( | |
// request: Request, | |
// env: Env, | |
// ctx: ExecutionContext | |
// ): Promise<Response> { | |
// const url = new URL(request.url); | |
// const key = url.pathname.slice(1); | |
// const img_url = `https://dvc-staging-public-misc.s3.amazonaws.com/${key}`; | |
// try { | |
// const response = await fetch(img_url); | |
// await env.MY_BUCKET.put(key, response.body); | |
// return new Response(`Put ${key} successfully!`); | |
// } catch (err) { | |
// return new Response("Fetch error", { | |
// status: 500, | |
// }); | |
// } | |
// }, | |
async fetch( | |
request: Request, | |
env: Env, | |
ctx: ExecutionContext | |
): Promise<Response> { | |
const url = new URL(request.url); | |
const key = url.pathname.slice(1); | |
const formData = new FormData(); | |
formData.append("url", `https://${key}`); | |
formData.append("id", key); | |
return await fetch( | |
`https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/images/v1`, | |
{ | |
method: "POST", | |
headers: { | |
Authorization: `Bearer ${env.API_TOKEN}`, | |
}, | |
body: formData, | |
} | |
); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment