reactjs - 将图像上传到firebase存储然后再次将其传输到firestore后等待url数组
问题描述
const sendImageToFirebase = (e) => {
const promises = []
const urlsArray = []
// productimage is an array of image files
productImage.forEach((image, i) => {
var storageRef = firebase.storage().ref();
var uploadTask = storageRef.child(`${userDetailsFirebase.uid}/` + Math.random()).put(image);
promises.push(uploadTask.on('state_changed',
(snapshot) => {
},
(error) => {
console.log("error");
},
async () => {
const downloadurl = await uploadTask.snapshot.ref.getDownloadURL()
urlsArray.push(downloadurl)
}
))
})
Promise.all(promises).then(res => {
db.collection("products").doc(idGeneratedforProduct).set(
{
imageURL: urlsArray, //array of image urls
},
).then(e => {
}).catch(error => console.log("Error while sendig items to Firebase"))
})
}
我想将多个图像上传到 Firebase 存储。这里sendImagToFirebase是reactJs中的普通函数,productimage是图片文件数组。我想等待每个图像文件的 URL,然后将它们作为数组存储到 firestore。我将不胜感激您对如何做到这一点的意见?
解决方案
您可以创建一个函数来接收ref
和file
并返回downloadURL
. 通过使用 a 为每个文件调用它,Promise.all
您将获得downloadURL
s 数组:
const uploadFileAndGetDownloadURL = async (ref, file) => {
const snap = await ref.put(file);
const downloadURL = await snap.ref.getDownloadURL();
return downloadURL;
};
const sendImageToFirebase = async (e) => {
const promises = [];
productImage.forEach((image, i) => {
var storageRef = firebase.storage().ref();
var ref = storageRef.child(`${userDetailsFirebase.uid}/` + Math.random());
promises.push(uploadFileAndGetDownloadURL(ref, image));
});
//Your array with the urls
const urlsArray = await Promise.all(promises);
};
推荐阅读
- javascript - 带有分页的Vue js画廊图像
- python-3.x - Python - 如何将多行写入文件?(列表,不是字符串)
- javascript - 为什么当它的处理程序返回一个数组时 jest mockImplementation 不起作用?
- c - 没有“=”的 K&R C 初始化在 gcc 中查找支持的选项
- android-studio - 导入项目时无法解析符号以及库树上缺少 Androidmanifest.xml 文件
- kendo-ui - 避免在 Kendo 对话框动作中创建闭包
- opencv - 将包含 jpeg 图像的文件夹转换为 hdf5
- text - MLCK在文本分析中是什么意思
- c - 当分配给“float”时,附加“f”何时会更改浮动常量的值?
- firebase - 突然 Firebase 事件未导出到 Bigquery