up
date
‣
vip
slug
post0704
type
Post
CreatedTime
Jul 6, 2024 11:53 AM
status
Published
tags
Code
summary
在 Cloudflare Workers KV图床,支持苹果捷径
Link
category
Notion
password
IP
Email
cloudflare workers应用系列之5 : KV 图床
cloudflare workers应用系列之5 : KV 图床
在 Cloudflare Workers 部署一个KV 图床
最近telegra.ph图床时断时续, 只得新找一个免费的图床,
发现cloudflare的KV就支持, 同样一个单一的workers文件, 简单易用.
1 新建一个kv空间,随便名字, 为了以后区分可以取名为 KV,
2 新建一个workers,把代码换成以下的代码.
Code
const APIKEY = "xxxxxxx"; //增加验证 addEventListener("fetch", (event) => { const { request } = event const headers = request.headers ////增加验证 const authorization = headers.get("Authorization") ////增加验证 if (!authorization || authorization !== `Bearer ${APIKEY}`) { return fetch("https://http.cat/401")} if (request.method === "POST") { return event.respondWith(WriteKV(request)) } else if (request.method === "GET") { return event.respondWith(ReadKV(request)) } else { // 如果不是 GET 和 POST 请求,则返回 500 return fetch("https://http.cat/500"); } }); /** * * @param {*} request 请求体 get https://xxx.com/xx.jpg * @returns */ async function ReadKV(request) { try { const { pathname } = new URL(request.url); const newpathname= pathname.substring(1) const value = await KV.get(newpathname,{ type: "stream" }) //默认为json.修改type变成文件 if (value === null) { return new Response("Value not found", {status: 404}); } return new Response(value, { headers: { "Content-Type": "image/png", }, }) } catch (e) { return new Response(e.message, {status: 500}); } } /** * * @param {*} request 请求体 post https://xxx.com * @returns */ async function WriteKV(request) { const formData = await request.formData(); const file = formData.get("file"); formData.append("file", file); const fname=file.name // 将 JSON 数据写入 KV 数据库 await KV.put(fname, file.stream()) const fileurl="https://pic.51xmi.com/"+fname return new Response(JSON.stringify({ fileurl }), { headers: { "Content-Type": "application/json" }, }); //return new Response(fileurl); }
3 把kv空间绑定到这个workers上. 设置 变量 KV , KV命名空间绑定
4 可选,设置,触发器, 自定义域名. 绑定一个域名,国内可用, 不绑定的话国内不可用.
Workers 好就好在一次部署,终生不用再管,所以特别适合这种服务。
部署之后,就可以get和post了.
可以在网页中直接调用, 也可以苹果捷径直接用
然后在kv空间就可以看到.