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 10GB of free storage and 10 million free accesses per month.
- Go to the Cloudflare Dashboard and go to the R2 page as shown in the figure.
- Select "Create Bucket".
- Give your bucket a name and click "Create".
- You have completed the creation on the following page.
- Return to the R2 homepage. Since we need to use the API for file transfer in the following text, you need to create your R2 API token by clicking "Manage R2 API Tokens".
- Click "Create API Token" as shown in the figure.
- Since 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 open until you have saved all the information on this page properly. Do not close the page, otherwise, you will need to rotate the API token to disable the old key. Refer to 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 upload.
- 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 place the
alist.exe
in 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 execution, it will look like the figure.
5. Open your browser and enter localhost:5244
to access 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 to copy.
7. Note that clicking or dragging the terminal interface of cmd with the left mouse button will enter the selection state, and the program will be blocked by the system. You need to click 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 a blocked program. Click 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 "Manage" at the bottom.
10. You will enter the interface 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 credentials.
12. Go to the console and click "Storage", as shown in the figure.
13. Select "Add", as shown in the figure.
14. Configure 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 incorrectly in 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 directories for your image hosting to categorize landscape and portrait images, etc., so that you can use Workers 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 and go to the Workers and Pages pages, as shown in the figure.
- Click "Create", select "Create Workers", choose a name, and click "Deploy".
- Click "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 the "Settings" - "Variables" section, find the R2 bucket binding and add your bucket. The variable name is
MY_BUCKET
.
-
In the "Settings" - "Triggers" section, add your custom domain for access.
- Access the effect, it will be different every time you refresh.
Use the <img> tag in HTML to reference it and achieve the effect at the beginning.#
For example: <img src="your_domain" alt="">