二叉树树

二叉树树

瞎几吧写

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

Result Image#

b1720fb74fa66d9a6a9753a15c8ace82

Principle#

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

Create 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.

67207de47fd66c3a64566231a5757493

  1. Select to create a bucket.
    22be740f9c09f433395cf44ee2072ae2

  2. Name your bucket and then click create.
    b8f5322a073a6e65efc5daa3db274245

  3. You will see the following page, indicating that the creation is complete.
    370c1bd865c0ea34bc12c321e423361c

  4. Return to the R2 homepage. Since we will need to use the API for file transfer later, create your R2 API token by clicking on Manage R2 API Tokens.
    88aa85191334d4e673cdf57f49c0d03f

  5. Click to create an API token, as shown.
    eef6602d0521e26e5a5636f1ae5edbb1

  6. Since we need this API to manage a single R2 bucket, select Object Read and Write, with detailed configuration as shown.
    da5bde896453ebf7c1d514353a15a7f6

  7. After creating the API token, a new page will display the token details, it will only be shown once!!! Keep this page until you have properly 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.
    13056795f88f8340f8e6a1ea9a7c634d

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

Add 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.
    6d5a96a227cde32176c195a42a5f4b6e

  2. Unzip the downloaded package and place alist.exe in an empty folder.

  3. Click the search box, type cmd, and press Enter. In cmd, type alist.exe server and do not close the window. After successful execution, it will look like this.
    641385871e58cea5accd5c70e982fa76

  4. Open a browser and enter localhost:5244 to access the AList console, as shown.

  5. Username: admin Password: in the cmd window, as shown. You can use the left mouse button to select content in the terminal and then right-click to copy.
    4bd36bb92ede40107f2db8929325d0e3

  6. Note that 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 note. The following image is an example of the program being blocked; right-click in the terminal interface to release it.

b047fd36f8ea15d7c1c533c1dfb86f44

  1. Now, you have successfully logged into AList as an administrator. Click on Manage at the bottom.
    a5c933183769e968da8f7effd3cc8e4a

  2. You will enter the interface as shown. Although AList runs locally, it is recommended to change your username and password.
    e632d8509e67e8345d96b6131522f9bc

  3. Change your account and password, and log in again with the new credentials.

  4. Enter the console, then click on Storage, as shown.
    fd8ccb8f3b74531ab3a55aceb4924a0f

  5. Select Add, as shown.
    f6df68a8a0a93d90bdf0781002a95324

  6. Detailed configuration as shown. The mount path is the display path for AList, it is recommended to use /R2/your_bucket_name, and the region is auto.
    b116f31084667ee13b971d528e3415af

  7. Return to the homepage and try uploading files; you will see that the speed is very fast.
    1218c2d5e3308da7820740575038cfda

  8. 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 the R2 path /ri/h as the directory for random landscape images and /ri/v as the directory for random portrait images.

Create Workers to Connect to R2#

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

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

  3. Select Edit Code.
    557544edf1b592e2a827b8df079eb141

  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!

  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.

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

  3. Add your custom domain for access.

714bbe91af89f6b46b0ce8c796cfeeac

  1. The access effect, which is different every time you refresh.
    7c637bc0ea95f955132060973884e22d

You can achieve the initial effect by using the HTML <img> tag#

For example: <img src="your_domain" alt="">
Random Image API

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