给出的错误:[未处理的承诺拒绝:Firebase错误:Firebase存储:字符串与格式'data_url'不匹配:必须格式化'data:[][;base64],(存储/无效格式(]
我可以将图像添加到数据库中,但它无法上传到firebase存储中。我把它改成了不同的媒体类型,但运气不好。我也厌倦了uploadBytes而不是uploadString,它可以工作,但没有图像显示。任何帮助都将不胜感激!
const uploadImageTops = async () => {
const docRef = await addDoc(collection(db, "tops"), {
username: "user",
apparel: "tops",
color: "black",
size: size,
timeStamp: serverTimestamp(),
});
const imageRef = ref(storage, `tops/${docRef.id}`);
await uploadString(imageRef, cameraImage, "data_url", {contentType:'image/jpg'})
.then(async (snapshot) => {
const downloadURL = await getDownloadURL(imageRef);
await updateDoc(doc(db, "tops", docRef.id), {
imageUrl: downloadURL,
});
})
.then(navigation.navigate("Home"));
};
在尝试上传图像时,react native和firebase存在一些问题。需要Blob将图像上传到firebase存储和firestore。在顶部添加blob,并确保在末尾关闭blob。
这个代码对我有效。
const uploadImageTops = async () => {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", cameraImage, true);
xhr.send(null);
});
const docRef = await addDoc(collection(db, "tops"), {
username: user,
apparel: "tops",
color: color,
size: size,
timeStamp: serverTimestamp(),
});
const imageRef = ref(storage, `tops/${docRef.id}`);
const metadata = {
contentType: "image/jpeg",
};
await uploadBytes(imageRef, blob, metadata)
.then(async (snapshot) => {
const downloadURL = await getDownloadURL(imageRef);
await updateDoc(doc(db, "tops", docRef.id), {
imageUrl: downloadURL,
});
blob.close();
})
.then(navigation.navigate("Home"));
};