banner
二叉树树

二叉树树的xLog

Protect What You Love!
telegram
x
github
bilibili
steam_profiles
email

Cloudflare R2+Workers! Set up your own cloud image hosting right away!

This article is a remake of: https://xfeed.app/notes/71448-15


Result Image#

a8d420168e3aff48d16074b9d9570b50_720

Principle#

The image source is hosted by Cloudflare R2, which connects to R2 through two Workers to display random landscape/portrait images. The static page references the Workers' URL to achieve the above interface.

Creating a Cloudflare R2 Bucket#

R2 is essentially an object storage. Cloudflare offers 10GB of free storage and 10 million free accesses per month.

  1. Go to the Cloudflare Dashboard, and navigate to the R2 page, as shown in the image image.

  2. Select to create a bucket image.

  3. Name your bucket and then click create image.

  4. You will see the following page, indicating that the creation is complete image.

  5. Return to the R2 homepage. Since we will need to use the API for file transfers later, create your R2 API token by clicking on Manage R2 API Tokens image.

  6. Click to create an API token, as shown image.

  7. Since we need this API to manage individual R2 buckets, select Object Read and Write, with detailed configuration as shown image.

  8. After creating the API token, a new page will display the token details, it will only be shown once!!! Keep this page open until you have securely saved all the information; do not close the interface, otherwise, you will need to rotate the API token to disable the previous old key, as shown image.

  9. Ensure you have securely saved your R2 API token, then proceed to the next step.

Adding Files to Your Bucket#

Since transferring files via the web interface is slow and does not support files larger than 300MB, we will use a locally deployed AList to connect to your R2 bucket for high-speed uploads.

  1. The author uses Windows. Go to AList - Github Release to download the latest executable for Windows, as shown image.

  2. Extract the downloaded zip file and place alist.exe in an empty folder.

  3. Click the search box, type cmd, and press Enter, as shown imageSnipaste_2024-08-27_05-03-46.

  4. In cmd, type alist.exe server and do not close the window. It should run successfully, as shown image.

  5. Open your browser and enter localhost:5244 to access the AList console, as shown image.

  6. Username: admin Password: in the cmd window, as shown. You can select content in the terminal with the left mouse button and then right-click to copy image.

  7. Note that in cmd, clicking or dragging the cmd terminal interface with the left mouse button will cause it to enter selection mode, blocking the program by the system. You need to right-click in the terminal interface to release it. If the process is blocked, the cmd process name will have an additional selection; please be aware. The image shows an example of the program being blocked; right-click in the terminal interface to release it image.

  8. Now, you have successfully logged into AList as an administrator image.

  9. Click on Manage at the bottom image.

  10. You will enter the interface shown in the image. Although AList runs locally, it is recommended to change your username and password image.

  11. Change your account and password, then log in again with the new credentials image.

  12. Enter the console and then click on Storage, as shown image.

  13. Select Add, as shown image.

  14. Detailed configuration as shown. The mount path is the display path for AList, it is recommended to use /R2/your_bucket_name, the region is auto, and the root folder path is / (the image is filled in incorrectly, Orz) image.

  15. Return to the homepage, as shown image.

  16. Try uploading a file, as shown image.

  17. You can see that the speed is very fast image.

  18. Create directories for your image hosting to categorize landscape and portrait images, etc., for later use with Workers to connect to R2. I will use /ri/h as the directory for random landscape images and /ri/v as the directory for random portrait images.

Creating Workers to Connect to R2#

  1. Go to the Cloudflare Dashboard, and navigate to the Workers and Pages page, as shown image.

  2. Click Create, select Create Workers, name it as you wish, and click Deploy image.

  3. Select Edit Code image.

  4. Paste the code (to create random landscape images):

export default {
  async fetch(request, env, ctx) {
    // R2 bucket configuration
    const bucket = env.MY_BUCKET;

    try {
      // List all objects in the /ri/h directory
      const objects = await bucket.list({ prefix: 'ri/h/' });

      // Randomly select an object from the list
      const items = objects.objects;
      if (items.length === 0) {
        return new Response('No images found', { status: 404 });
      }
      const randomItem = items[Math.floor(Math.random() * items.length)];

      // Get the selected object
      const object = await bucket.get(randomItem.key);

      if (!object) {
        return new Response('Image not found', { status: 404 });
      }

      // Set appropriate Content-Type
      const headers = new Headers();
      headers.set('Content-Type', object.httpMetadata.contentType || 'image/jpeg');

      // Return image content
      return new Response(object.body, { headers });
    } catch (error) {
      console.error('Error:', error);
      return new Response('Internal Server Error', { status: 500 });
    }
  },
};
  1. Click the file icon on the left image.

  2. Fill in wrangler.toml with:

[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "114514"
  1. Save the changes and click Deploy in the upper right corner image.

  2. In Settings - Variables, find the R2 bucket binding, and add your bucket; the variable name is the aforementioned MY_BUCKET image.

  3. In Settings - Triggers, add your custom domain name for access imageimage.

  4. The access effect is different every time you refresh Snipaste_2024-08-27_06-12-53Snipaste_2024-08-27_06-12-43.

You can achieve the initial effect by using the HTML tag#

For example: <img src="your domain" alt="">
image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.