Result 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.
- Go to the Cloudflare Dashboard, go to the R2 page as shown in the figure
- Select Create Bucket
- Give your bucket a name and click Create
- You have already created it when you enter the following page
- 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
- Click Create API Token as shown in the figure
- Because we need this API to manage a single R2 bucket, select Object Read and Write, and configure it as shown in the figure
- 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
- 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.
- I am using Windows. Go to AList - Github Release to download the latest executable file for Windows, as shown in the figure
- Extract the downloaded zip file and put the
alist.exe
into an empty folder - Click the search box, type cmd and press Enter, as shown in the figure
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
5. Open the browser and enter localhost:5244
to enter the AList console, as shown in the figure
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.
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
8. Now, you have successfully logged in to AList as an administrator,
9. Click the bottom Management
10. You will enter the interface as shown in the figure. Although AList runs locally, it is recommended to change your username and password
11. Change the username and password, and log in again with the new password
12. Go to the console and click Storage, as shown in the figure
13. Select Add, as shown in the figure
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)
15. Go back to the homepage, as shown in the figure
16. Try uploading a file, as shown in the figure
17. You can see that the speed is very fast
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#
- Go to the Cloudflare Dashboard, go to the Workers and Pages pages, as shown in the figure
- Click Create, select Create Workers, choose a name, and click Deploy
- Select Edit Code
- 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 });
}
},
};
- Click the file icon on the left
- Fill in
wrangler.toml
:
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "114514"
-
Save the changes and click Deploy in the upper right corner
-
In Settings-Variables, find the R2 bucket binding and add your bucket. The variable name is
MY_BUCKET
-
In Settings-Triggers, add your custom domain name for access
- Access the effect, it will be different every time you refresh
Use the <img> tag in HTML to achieve the effect at the beginning#
For example: <img src="your domain name" alt="">