如何在上传文件至Firebase Storage前获取Firestore自动生成文档ID并作为存储引用(Web)
解决方案
核心思路是先生成Firestore自动ID,再用这个ID作为Storage的存储路径,调整代码执行顺序即可实现需求:
修改后的代码
try { // 1. 先生成Firestore文档引用,获取自动生成的ID const organization_doc_ref = doc(collection(this.firestore, 'organizations')); const autoGeneratedId = organization_doc_ref.id; // 2. 用自动ID构造Storage存储引用 const storageRef = ref(this.storage, `organizations/${autoGeneratedId}`); // 3. 上传文件到Storage并获取下载URL await uploadBytes(storageRef, blob); console.info('Uploaded a blob or file!'); organization.logo_url = await getDownloadURL(storageRef); // 4. 构建批量写入操作 const batch = writeBatch(this.firestore); batch.set(organization_doc_ref, organization); const usernameDocRef = doc(this.firestore, 'usernames', organization.username); batch.set(usernameDocRef, { uid: autoGeneratedId }); // 5. 提交批量写入 await batch.commit(); console.log('Organization successfully created...'); } catch (error) { console.error('Error writing document: ', error); // 可选:如果批量写入失败,可以删除已上传的文件 // const storageRef = ref(this.storage, `organizations/${organization_doc_ref?.id}`); // await deleteObject(storageRef); }
关键改动说明
- 调整执行顺序:先创建Firestore文档引用,提前拿到自动生成的ID,避免后续无法关联Storage路径和文档ID
- 统一ID使用:全程复用
autoGeneratedId(或organization_doc_ref.id),确保Storage路径和Firestore文档ID完全一致 - 简化异步代码:去掉
uploadBytes后的.then(),直接用await处理异步操作,代码更简洁易读
可选优化点
如果担心批量写入失败后,Storage中残留无用文件,可以在catch块中添加删除文件的逻辑(代码中已注释),保证数据一致性。
内容的提问来源于stack exchange,提问作者syahiruddin
相关产品推荐
相关产品推荐

