3001免费图床 cf workers源码代码分享
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
if (request.method === 'GET') {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
} else if (request.method === 'POST') {
const formData = await request.formData()
const file = formData.get('file')
const response = await fetch("https://www.freebuf.com/fapi/frontend/upload/image", {
method: 'POST',
headers: {
"Accept": "application/json, text/plain, */*",
"Referer": "https://www.freebuf.com/write",
"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
},
body: formData
})
const data = await response.json()
let imageUrl = data.data.url.replace(/\\/g, "").replace('!small', '');
// 使用正则确保URL的开头是https:,并且没有重复的斜线
imageUrl = imageUrl.replace(/^https?:/, 'https:');
imageUrl = imageUrl.replace(/([^:]\/)\/+/g, "$1");
return new Response(JSON.stringify({ imageUrl }), {
headers: { 'Content-Type': 'application/json' }
})
}
}
const html = `
<!DOCTYPE html>
<html>
<head>
<title>3001免费图床</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
font-family: Arial, sans-serif;
}
#resultUrl {
margin-top: 20px;
}
hr {
width: 100%;
max-width: 500px;
}
.developer {
display: none;
}
</style>
</head>
<body>
<h1>3001免费图床</h1>
<input type="file" id="fileInput" />
<button onclick="uploadFile()">上传</button>
<hr>
<p>建议上传5M以内的JPG/PNG文件</p>
<p>仅供学习JS使用,违规使用后果自负</p>
<hr>
<p id="resultUrl">URL: <a href="#" id="urlLink" target="_blank"></a></p>
<footer>
<hr>
<p>这是页脚</p>
</footer>
<script>
async function uploadFile() {
const fileInput = document.getElementById('fileInput');
const formData = new FormData();
formData.append('file', fileInput.files[0]);
const response = await fetch('/', {
method: 'POST',
body: formData
});
const data = await response.json();
const resultUrl = document.getElementById('urlLink');
resultUrl.href = data.imageUrl;
resultUrl.textContent = data.imageUrl;
}
</script>
</body>
</html>
`