banner
AcoFork

AcoFork

LOVETOLOVE

Cloudflare R2+Workers! Build your own cloud-based image hosting platform now!

Result Image#

image

Principle#

The image source is hosted by Cloudflare R2 and connected to R2 through two Workers to display random images. The static page references the URL of Workers to achieve the above interface.

Create a Cloudflare R2 bucket#

R2 is actually an object storage. Cloudflare provides 10G of free storage and 10 million free accesses per month.

  1. Go to the Cloudflare Dashboard, go to the R2 page as shown in the figure
    image
  2. Select Create Bucket
    image
  3. Give your bucket a name and click Create
    image
  4. You have already created it when you enter the following page
    image
  5. Return to the R2 homepage. Because we need to use the API for file transfer in the following text, you need to create your R2 API token. Click Manage R2 API Tokens
    image
  6. Click Create API Token as shown in the figure
    image
  7. Because we need this API to manage a single R2 bucket, select Object Read and Write, and configure it as shown in the figure
    image
  8. After creating the API token, the new page will display the details of the token, it will only be displayed once!!! Keep this page until you have saved all the information on this page properly. Do not close the page, otherwise, you need to rotate the API token to disable the old key. As shown in the figure
    image
  9. Make sure you have saved your R2 API token properly and proceed to the next step

Add files to your bucket#

Because the web interface transfers files slowly and does not support files larger than 300MB. Here, we use locally deployed AList to connect to your R2 bucket for high-speed uploading.

  1. I am using Windows. Go to AList - Github Release to download the latest executable file for Windows, as shown in the figure
    image
  2. Extract the downloaded zip file and put the alist.exe into an empty folder
  3. Click the search box, type cmd and press Enter, as shown in the figure
    image

Snipaste_2024-08-27_05-03-46
4. Enter alist.exe server in the cmd and do not close the window. After successful operation, it will be as shown in the figure
image
5. Open the browser and enter localhost:5244 to enter the AList console, as shown in the figure
image
6. Username: admin Password: in the cmd window, as shown in the figure. You can use the left mouse button to select content in the terminal and then right-click the mouse to copy.
image
7. Note that clicking or dragging the terminal interface of cmd with the left mouse button in cmd will enter the selection state, and the program will be blocked by the system. You need to press the right mouse button in the terminal interface to release it. If the process is blocked, the process name of cmd will have an additional Select, please note. The figure shows an example of the program being blocked, press the right mouse button in the terminal interface to release it
image
8. Now, you have successfully logged in to AList as an administrator,
image
9. Click the bottom Management
image
10. You will enter the interface as shown in the figure. Although AList runs locally, it is recommended to change your username and password
image
11. Change the username and password, and log in again with the new password
image
12. Go to the console and click Storage, as shown in the figure
image
13. Select Add, as shown in the figure
image
14. Configure it as shown in the figure. The mount path is the display path of AList, it is recommended to use /R2/your bucket name, the region is auto, and the root folder path is / (it is filled in reverse on the figure)
image
15. Go back to the homepage, as shown in the figure
image
16. Try uploading a file, as shown in the figure
image
17. You can see that the speed is very fast
image
18. Create a directory for your image bed to classify landscape and portrait images, so that Workers can be used to connect to R2. In the following text, I will use /ri/h as the directory for random landscape images and /ri/v as the directory for random portrait images.

Create Workers and connect to R2#

  1. Go to the Cloudflare Dashboard, go to the Workers and Pages pages, as shown in the figure
    image
  2. Click Create, select Create Workers, choose a name, and click Deploy
    image
  3. Select Edit Code
    image
  4. Paste the code (create random landscape image):
export default {
  async fetch(request, env, ctx) {
    // R2 bucket configuration
    const bucket = env.MY_BUCKET;

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

      // Select a random 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 the appropriate Content-Type
      const headers = new Headers();
      headers.set('Content-Type', object.httpMetadata.contentType || 'image/jpeg');

      // Return the 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:
[[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 MY_BUCKET
    image

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

image

  1. Access the effect, it will be different every time you refresh
    Snipaste_2024-08-27_06-12-53

Snipaste_2024-08-27_06-12-43

Use the <img> tag in HTML to achieve the effect at the beginning#

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

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