Last active
September 2, 2024 08:04
-
-
Save foru17/7591b29a774cfa1d82ebe6b16d0232a9 to your computer and use it in GitHub Desktop.
zip files and download by cloudlfare worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 通过 Cloudflare Worker 批量打包和下载现存文件 | |
// curl -X POST https://your-worker-endpoint/create-zip \ | |
// -H "Authorization: Bearer YOUR_AUTH_SECRET" \ | |
// -H "Content-Type: application/json" \ | |
// -d '{ | |
// "filePaths": [ | |
// "path/to/file1.jpg", | |
// "path/to/file2.png", | |
// "path/to/file3.pdf" | |
// ] | |
// } | |
import JSZip from 'jszip'; | |
interface Env { | |
MY_BUCKET: R2Bucket; | |
AUTH_SECRET: string; | |
BUCKET_HOST_NAME: string; | |
} | |
export default { | |
async fetch(request, env: Env): Promise<Response> { | |
if (request.method === 'POST' && new URL(request.url).pathname === '/create-zip') { | |
const auth = request.headers.get('Authorization'); | |
const expectedAuth = `Bearer ${env.AUTH_SECRET}`; | |
if (!auth || auth !== expectedAuth) { | |
return new Response('Unauthorized', { status: 401 }); | |
} | |
const requestData = await request.json(); | |
const filePaths = requestData.filePaths; | |
if (!Array.isArray(filePaths) || filePaths.length === 0) { | |
return new Response('Invalid input', { status: 400 }); | |
} | |
try { | |
const zip = new JSZip(); | |
// Download and add files to ZIP | |
for (const path of filePaths) { | |
const object = await env.MY_BUCKET.get(path); | |
if (object === null) { | |
return new Response(`File not found: ${path}`, { status: 404 }); | |
} | |
const content = await object.arrayBuffer(); | |
zip.file(path.split('/').pop(), content); | |
} | |
// Generate ZIP file | |
const zipContent = await zip.generateAsync({ type: 'arraybuffer' }); | |
// Upload ZIP file to R2 | |
const zipFileName = `bundle-${Date.now()}.zip`; | |
await env.MY_BUCKET.put(zipFileName, zipContent); | |
const zipFileUrl = `${env.BUCKET_HOST_NAME}/${zipFileName}`; | |
return new Response(JSON.stringify({ url: zipFileUrl }), { | |
headers: { 'Content-Type': 'application/json' }, | |
}); | |
} catch (error) { | |
return new Response(`Error: ${error.message}`, { status: 500 }); | |
} | |
} | |
// Fetch from R2 bucket | |
const url = new URL(request.url); | |
const key = url.pathname.slice(1); | |
const object = await env.MY_BUCKET.get(key); | |
if (object === null) { | |
return new Response('Object Not Found', { status: 404 }); | |
} | |
const headers = new Headers(); | |
object.writeHttpMetadata(headers); | |
headers.set('etag', object.httpEtag); | |
return new Response(object.body, { | |
headers, | |
}); | |
}, | |
} satisfies ExportedHandler<Env>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment