Store and Deliver images with Cloudflare R2 backend Cloudflare Workers.
- Deploy r2-image-worker to Cloudflare Workers.
- Make base64 strings from the image file such as
.png
,jpg
, orgif
. PUT
the base64 strings to r2-image-worker.- An image binary will be stored in Cloudflare R2 storage.
- r2-image-worker will respond the key of the stored image.
abcdef.png
- r2-image-worker serve the images on
https://r2-image-worker.username.workers.dev/abcdef.png
- Images will be cached on Cloudflare CDN.
User => Image => base64 => r2-image-worker => R2
User <= Image <= r2-image-worker <= CDN Cache <= R2
- Cloudflare Account
- Wrangler CLI
- (Custom domain * Cache API is not available in
*.workers.dev
domain)
First, git clone
git clone https://github.com/yusukebe/r2-image-worker.git
cd r2-image-worker
Create R2 bucket:
wrangler r2 bucket create images
Copy wrangler.example.toml
to wrangler.toml
:
cp wrangler.example.toml wrangler.toml
Edit wrangler.toml
.
Secret variables are:
USER
- User name of basic authPASS
- User password of basic auth
To set these, use wrangler secret put
command:
wrangler secret put USER
To publish to your Cloudflare Workers:
npm run deploy
Header:
To pass the Basic Auth, add the Base64 string of "user:pass" to Authorization
header.
Authorization: Basic ...
Body:
Value of body
is Basic64 string of image binary.
{
"body": "Base64 Text..."
}
- Download a simple image
wget https://www.bing.com/th?id=OHR.Unesco50_ZH-CN3652927413_UHD.jpg -O /tmp/1.jpg
- Upload to u endpoint.
echo '{"body" : "'"$( cat /tmp/1.jpg | base64)"'"}' | curl -XPUT -H "Content-Type: application/json" -d @- https://change_user_here:change_pass_here@change_url_here/upload -vvv
- Visit the image
https://change_user_here:change_pass_here@change_url_here/image_returned_in_step2
Awesome!!!
Setting shortcuts like this:
Shared shortcut: Upload to Cloudflare. Prior to utilizing it, input the domain and user:pass into the designated text field.
Yusuke Wada https://github.com/yusukebe
MIT