Basically I'm using next.js and I'm making a program that generates images using Openai's Dalle2 API (artificial intelligence), and then uploads it onto my firebase storage. How do I download these images when they are generated and upload them to the firebase storage? Everytime i try, I just end up getting a 'application/octet-stream' file type uploaded and it doesn't work.
This is my code:
const [selectedFile, setSelectedFile] = useState(null);
const generateImage = async () => {
console.log('openai image start')
const prompt = captionRef.current.value
try {
const response = await openai.createImage({
prompt: prompt,
n: 1,
size: "256x256",
})
const imageUrl = response.data.data[0].url
console.log('openai image generated')
setSelectedFile(imageUrl)
console.log(selectedFile)
} catch (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.data);
} else {
console.log(error.message);
}
}
}
const uploadPost = async () => {
if (loading) return;
setLoading(true);
//create post and add to firestore posts collection
//get post id for new post
//upload image to firebase storage with post id
//get a download url from firebase storage and update original post with image
const docRef = await addDoc(collection(db, 'posts'), {
username: session.user.username,
caption: captionRef.current.value,
profileImg: session.user.image,
timestamp: serverTimestamp()
})
console.log("New doc added with ID", docRef.id);
console.log(selectedFile)
//**PROBLEM**
const imageRef = ref(storage, `posts/${docRef.id}/image`)
await uploadBytes(imageRef, selectedFile).then(async snapshot => {
const downloadURL = await getDownloadURL(imageRef)
await updateDoc(doc(db, 'posts', docRef.id), {
image: downloadURL
})
})
setLoading(false)
setSelectedFile(null)
}