简体   繁体   中英

How to upload an image to Cloudflare Images from Node using fetch?

I'm trying to upload an image from my computer to Cloudflare Images using Node and the fetch API. They provided me with a curl command that works fine.

curl -X POST -F file=@./<file_name> -H "Authorization: Bearer <api_token>" https://api.cloudflare.com/client/v4/accounts/<domain_id>/images/v1

When I tried to convert it to fetch, Cloudflare keeps sending me a 400 in their response.

const cloudflarePostBody = new FormData();
cloudflarePostBody.append("file", fs.createReadStream("testing.jpeg"));

const cloudflareResponse = await fetch("https://api.cloudflare.com/client/v4/accounts/<my_id>/images/v1", {
    method: "POST",
    headers: {
        Authorization: `Bearer ${cloudflareApiToken}`,
        "Content-Type": "multipart/form-data"
    },
    body: cloudflarePostBody,
});

My guess is that I'm doing something wrong with how I'm reading the file with createReadStream , but a lot of the examples I've looked up showed exactly that. Does anyone have any advice? Thanks in advance.

Try fs.readFile() instead of fs.createReadStream() :

  fs.readFile("testing.jpeg", (err, data) => {
    if (err) throw err;
    cloudflarePostBody.append("file", new Blob([data]), "testing.jpeg");
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM