Self-Host File Storage on Cloudflare R2 with Worker

Preface

But the R2 management page doesn't show image previews in a very intuitive way.

We can use a worker to manage them

Practice

Considering that there may be many and large images, it is recommended to enable Cloudflare's Image Transformation feature

First, you need to have a domain hosted on Cloudflare.

Enable the Image Transformation feature


Set a custom domain for R2

Do you remember this page?

Enter a subdomain of your domain. For example, r2test.xxxx.xxxx
After a while, it will look like this, indicating it has taken effect.

Set the CORS policy

[
  {
    "AllowedOrigins": [
      "*"
    ],
    "AllowedMethods": [
      "PUT",
      "GET",
      "HEAD",
      "DELETE"
    ],
    "AllowedHeaders": [
      "*"
    ]
  }
]
* Note, to be honest this is a bit blunt here, but it's not a big deal. 

Some information about your R2 now

On the ShareX S3 uploader page.
Access key ID
Secret access key
Endpoint
Bucket name
Custom domain

Create a Cloudflare Worker




Edit the Worker's script content


Delete all the original content


Replace it with: https://github.com/crazypeace/file-r2-worker/blob/main/worker.js 's content

Modify the admin panel access password:
WORKER_PASSWORD = "suibianshezhishenme"   // change it to whatever you like

Set R2 parameters
* In the ShareX S3 uploader page, the Secret access key cannot be copied out

Save and deploy

Top right corner

Use the file-r2-worker file storage site

Visit your worker domain with a browser or click the visit link

Showing 404 is a normal feature; a password is set to keep it from public use.

Add the password as a path after the worker domain, e.g.  
https://divine-voice-e752.crazypeace.workers.dev/suibianshezhishenme
The interface will then display properly

If you already have files saved in your R2, you can click the "load R2 to localStorage" button.

If you want to delete an image, click the X button.

========

Postscript

If you want to use Cloudflare's Image Transformation feature to generate thumbnails,
R2_PUBLIC_URL should use your R2 custom domain

If you want to share it with multiple people, then only upload on this admin page, so that each person only sees their own uploaded images in the list. At the same time, set
LOAD_R2_BUTTON = "false" 
 
This way, images uploaded by others won't be loaded via the load R2 button.
* However, the admin page actually has the R2 api token, which can be used to operate on R2, so you can only share it with people you trust. Disabling the load R2 button on the page is just to prevent misoperations.

========

Related recommendations


Comments