Getting an error "'image' is a required property" while generating image variations using openai and JavaScript

159 views Asked by At

I am getting an error "'image' is a required property" while trying to generate image variations in JavaScript. Here is my code.

//Function for sending http request
async function upload(formData) {
  try {
    const response = await fetch("https://api.openai.com/v1/images/variations", {
      method: "POST",
      body: formData,
      headers: {"Content-Type": "multipart/form-data", "Authorization": "Bearer" + " " + api_key}
    });
    const result = await response.json();
    console.log("Success:", result);
  } catch (error) {
    console.error("Error:", error);
  }
}
  
  // Calling it. Here I am using image data. I am sending the image but still it says 
  //that image is required

  const form_data = new FormData();
  form_data.append("image",imageData);
  form_data.append("n",1);
  form_data.append("size",'1024x1024');

  upload(form_data);

Please help me? Thanks.

1

There are 1 answers

2
Quentin On BEST ANSWER

The multipart/form-data content type has a mandatory boundary parameter which tells the recipient where each of the multiple parts begins and ends. You are omitting it so the recipient can't see the different parts and thus can't find image among them. You also can't know what the correct value for the boundary parameter is.

Under normal circumstances, fetch will generate the Content-Type header using the FormData object, but you are overriding it. Don't do that.