我正在使用firebase和react.js创建一个应用程序。当我重新加载应用程序时,只会显示最后一个图像,而应该将它们全部加载到第一页。下面是问题所在的handleUpload函数(更新):
const handleUpload = () => {
//const storageRef = ref(storage, `images/${image.name}`);
const randomId = doc(collection(db, "temp")).id;
const storageRef = ref(storage, `images/${randomId}`);
const uploadTask = uploadBytesResumable(storageRef, image);
uploadTask.on(
"state_changed",
(snapshot) => {
//Progress function ... (shows the load bar)
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
},
(error) => {
//Error Function...
console.log(error);
alert(error.message);
},
async () => {
//complete function
const url = await getDownloadURL(storageRef);
const docRef = await addDoc(collection(db, "posts"), {
imageURL: url,
caption: caption,
username: username,
timestamp: serverTimestamp()
});
console.log("THE APP HAS POSTED");
setProgress(0);
setCaption('');
setImage(null);
setUrl('');
}
)
}下面是我的存储控制台,在重新启动和发布来自iPhone的2张照片之后:

那里应该有两张照片,但只有最新的一张,名字是${image.name},我不明白,因为我把这一行注释掉了。
注意:这个问题只发生在有人上传到手机上,因为手机上没有文件名,只有相机卷上的照片。有什么办法可以解决这个问题吗?
发布于 2022-01-04 18:25:30
Firebase存储不会为新文件生成随机ID。上传时必须指定文件名。您可以使用一个包(如UUID,甚至Firestore )生成随机ID,如下所示:
const randomId = doc(collection(db, "temp")).id
const storageRef = ref(storage, `images/${randomId}`);还要确保在文件名末尾添加文件扩展名。
你想上传同名的图片吗?在这种情况下,它将用该名称覆盖现有的图像。
https://stackoverflow.com/questions/70583403
复制相似问题