Skip to content

Instantly share code, notes, and snippets.

@abouthalf
Created December 9, 2024 18:54
Show Gist options
  • Select an option

  • Save abouthalf/229659121c62a1c8b06bd928c652bb5a to your computer and use it in GitHub Desktop.

Select an option

Save abouthalf/229659121c62a1c8b06bd928c652bb5a to your computer and use it in GitHub Desktop.
Quick Script for uploading files to Cloudflare Image Storage (and formatting the results as markdown and JSON) NOT for giant sets of files.
import "dotenv/config";
import { program } from "commander";
import { globbySync } from "globby";
import fs from "fs/promises";
import { basename, extname } from "path";
import mimext from "mimext";
async function main() {
program
.version("0.0.1")
.option("-s, --src <input>", "Path to directory of images to upload", ".");
program.parse();
// base path to check for images
const { src } = program.opts();
const searchPath = `${src}/**/*.{jpeg,jpg,png,webp,svg,gif}`;
const paths = globbySync([searchPath]);
const API = `https://api.cloudflare.com/client/v4/accounts/{process.env.CLOUDFLARE_ACCOUNT_ID}/images/v1`;
const out = [];
// for each path,
// read the file, get the name, get the file extension,
// determine the mime type
// create a Blob with the file data
// create a FormData object, with the Blob as a file upload
// Post to Cloudflare
for await (const path of paths) {
const stats = await fs.stat(path);
const mime = mimext(extname(path));
const title = basename(path);
const buffer = await fs.readFile(path);
const formData = new FormData();
const blob = new Blob([buffer], { type: mime });
formData.append("file", blob, basename(path));
const response = await fetch(API, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CLOUDFLARE_IMAGES_API_TOKEN}`,
},
body: formData,
});
if (!response.ok) {
console.log(response.status, response.statusText);
const text = await response.text();
throw new Error(
`Response Not OK: Failed to upload image: ${path}, ${response.status} ${response.statusText}, ${text}`
);
}
const json = await response.json();
const {
result: { id, variants },
success,
} = json;
if (!success) {
console.error(json);
throw new Error(`Failed to upload image: ${path}`);
}
out.push({
id,
variants,
// or format a image transformation URL to your liking...
markdown: `![${title}](${variants[0])`,
});
}
// data
await fs.writeFile(`${src}/uploads.json`, JSON.stringify(out, null, 2));
// markdown
const md = out.map(({ markdown }) => markdown).join("\n\n");
await fs.writeFile(`${src}/uploads.md`, md);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment