尝试将图像上传到 GraphCMS 时出现错误 400

时间:2021-08-01 15:16:34

标签: javascript node.js reactjs formik

我正在尝试在提交表单时上传图片,当我尝试将图片作为 base64 发送到上传端点时出现问题。

// Form input for image uploads
<input
  name="main_image"
  type="file"
  accept="image/jpg, image/png, image/jpeg, image/webp"
  onChange={(event) => {
   const file = event.target.files[0];
   const reader = new FileReader();
   reader.onload = function (event) {
    console.log(event.target.result);
    setFieldValue("main_image", event.target.result); // This is what I send to the backend
   };

  if (file && file.type.match("image.*")) {
    reader.readAsDataURL(file); // I send it as Base64 to show the image in the website
  }
}}
/>

当表单被提交时,它会运行一个函数在后端开始上传图片

// Backend function to upload image

const { image } = req.body;

  const imgBuffer = Buffer.from(
    image.replace(/^data:image\/(png|gif|jpeg);base64,/, ""),
    "base64"
  );

  form.append("fileUpload", imgBuffer);


  const response = await fetch(`${process.env.GRAPH_DOMAIN}/upload`, {
    method: "POST",
    headers: {
      authorization: "auth token",
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: form,
  });

// Do stuff with the response

我尝试将图像作为 base64 发送,但它不起作用,文档只说对非 URL 图像使用 fs.createReadStream('path/to/file.png'),并且将图像作为 base64 作为 URL 发送不起作用

GraphCMS 文档链接:https://graphcms.com/docs/api-reference/content-api/assets#upload-by-file

0 个答案:

没有答案