简体   繁体   English

如何使用 fetch 从 Node 将图像上传到 Cloudflare Images?

[英]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.我正在尝试使用 Node 和 fetch API 将图像从我的计算机上传到 Cloudflare Images。他们为我提供了一个运行良好的 curl 命令。

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.当我尝试将其转换为 fetch 时,Cloudflare 一直在回复中向我发送 400。

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.我的猜测是我在使用createReadStream读取文件的方式上做错了,但我查过的很多例子都表明了这一点。 Does anyone have any advice?有人有建议吗? Thanks in advance.提前致谢。

Try fs.readFile() instead of fs.createReadStream() :尝试fs.readFile()而不是fs.createReadStream()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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