My application has PNG images stored as Buffers in Node.js. I would like to upload these images to Cloudflare Images.
The docs for Cloudflare Images explain how to upload an image through a dashboard or through an HTML form, but not how to upload images programmatically in Node.js.
Link to relevant Cloudflare docs: https://developers.cloudflare.com/images/cloudflare-images/upload-images/
Is there a way to directly upload images from Node.js to Cloudflare Images? If not, is there an easy way to simulate HTML form submission with a Node.js fetch?
I don't know why instructions on how to do this are not provided in the Cloudflare Images documentation. "Direct upload" as commented in the question is not what the OP is asking for.
import fs from 'fs';
import dotenv from 'dotenv/config';
const image = fs.readFileSync('./image.jpg');
const blob = new Blob([image]);
const formData = new FormData();
formData.append("file", blob, "filename_for_cloudflare");
try {
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/images/v1`, {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.CLOUDFLARE_BEARER_TOKEN}`,
},
body: formData,
});
// Your image has been uploaded
// Do something with the response, e.g. save image ID in a database
console.log(await response.json())
} catch (error) {
console.error(error)
}
We can upload images to the aforementioned service by making a POST request of type multipart/form-data with the JavaScript Fetch API:
Buffer
format. The native NodeJS fs.readFileSync()
method would be a way to do itBlob
with the image BufferFormData
for our POST requestappend()
to the FormData
a key named "file"
with the value of the Blob
variableappend()
methodbody
of the request as formDataIn this scenario, uploading is rather straightforward because we already have the image as a Buffer in NodeJS. In case somebody ever needs it, here is a GitHub gist with a more elaborate example on how to upload the image with a file picker client side in Svelte, get it from an Express.js server with multer, and make the actual API call to Cloudflare. This call should preferably be made server-side in order to not expose your environment variables to the client.