Skip to main content

React Client code to upload image to backend

Code​

  • Function to call endpoint (see s3 upload for Server side code)
const uploadToBackend = (blobUrl) => {
fetch(blobUrl)
.then((response) => response.blob())
.then((blobData) => {
const file = new File([blobData], "image.jpg", { type: blobData.type });
console.log(file);
const formData = new FormData();
formData.append("image", file, blobUrl);

fetch("/api/s3/upload", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
console.log("Upload response:", data);
})
.catch((error) => {
console.error("Upload error:", error);
});
})
.catch((error) => {
console.error("Fetch error:", error);
});
};

Upload Blob Image (How to handle blobs)​

  • Assuming that you have an endpoint that returns a blob of image.
const fetchImage = async () => {
try {
const response = await fetch(`/api/generator?prompt=${text}`);
if (!response.ok) {
throw new Error("Failed to fetch image");
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
uploadToBackend(url);
} catch (error) {
console.error("Error fetching image:", error);
}
};