Skip to content

Examples

Cloudflare Worker: proxy and re-encode an image as a data URI

Section titled “Cloudflare Worker: proxy and re-encode an image as a data URI”
import { imageUrlToBase64 } from "edge64";
export default {
async fetch(request) {
const { searchParams } = new URL(request.url);
const imageUrl = searchParams.get("url");
if (!imageUrl) {
return new Response("Missing url param", { status: 400 });
}
try {
const { dataUri } = await imageUrlToBase64(imageUrl);
return Response.json({ dataUri });
} catch (err) {
return new Response(err.message, { status: 502 });
}
},
};

Storing an uploaded image as base64 in D1 or KV

Section titled “Storing an uploaded image as base64 in D1 or KV”
import { bytesToDataUri } from "edge64";
async function storeUpload(request, env) {
const buffer = await request.arrayBuffer();
const dataUri = bytesToDataUri(buffer);
await env.KV.put(`upload:${crypto.randomUUID()}`, dataUri);
return new Response("stored");
}

Round-tripping a stored data URI back to bytes

Section titled “Round-tripping a stored data URI back to bytes”
import { base64ToBytes } from "edge64";
async function serveUpload(key, env) {
const dataUri = await env.KV.get(key);
if (!dataUri) return new Response("not found", { status: 404 });
const bytes = base64ToBytes(dataUri);
const mime = dataUri.slice(5, dataUri.indexOf(";"));
return new Response(bytes, { headers: { "content-type": mime } });
}

Sniffing a MIME type before trusting a file extension

Section titled “Sniffing a MIME type before trusting a file extension”
import { sniffMimeType } from "edge64";
function validateUpload(bytes) {
const mime = sniffMimeType(bytes);
if (!mime) {
throw new Error("Unrecognized or unsupported image format");
}
return mime;
}

This is useful for rejecting files that claim to be images by extension but aren’t, since the check reads the actual file bytes instead of trusting user input.