javascriptnode.jsformscloudflare

How do I upload an image to Cloudflare Images from Node.js?


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?


Solution

  • 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.

    What you need

    Code to programmatically upload an image to Cloudflare Images in NodeJS

    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)
    }
    

    Code explanation

    We can upload images to the aforementioned service by making a POST request of type multipart/form-data with the JavaScript Fetch API:

    1. Get an image in Buffer format. The native NodeJS fs.readFileSync() method would be a way to do it
    2. Create a new variable of type Blob with the image Buffer
    3. Create a new variable of type FormData for our POST request
    4. append() to the FormData a key named "file" with the value of the Blob variable
    5. You may also optionally include a filename for the image on Cloudflare as a third argument of the append() method
    6. Make the actual fetch request. I recommend using a try-catch block. You need to include your Cloudflare account ID in the URL for the Cloudflare API. It is also mandatory to have an Authorization header with the bearer token. The image itself goes in the body of the request as formData

    Additional Info

    In 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.