Utilizing the Dall E Create image variation API has been a bit challenging for me. Every time I send a post request, I encounter this particular error:
error: { "code": null, "message": "'image' is a required property", "param": null, "type": "invalid_request_error" }
I have incorporated this code in my next.js project:
const [selectedImage, setSelectedImage] = useState<File | null>(null);
const endpoint = "https://api.openai.com/v1/images/variations";
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!selectedImage) {
toast(t("alert"), {
icon: "❌",
});
return;
}
const imageSize =
selectedValue === "Small"
? "256x256"
: selectedValue === "Medium"
? "512x512"
: "1024x1024";
setLoading(true);
const headers = {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_API_KEY}`,
};
const formData = new FormData();
formData.append("image", selectedImage);
formData.append("n", String(number));
formData.append("size", imageSize);
formData.append("response_format", "url");
try {
const response = await fetch(endpoint, {
method: "POST",
body: formData,
headers: headers,
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
throw error;
} finally {
setLoading(false);
}
}
The process of storing the image in the state looks like this:
const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files && event.target.files[0];
if (file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
setSelectedImage(file);
};
}
};
I would appreciate any insights on where I might be going wrong here 🙏