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