我想在Firebase存储中添加一个图像(用户生成的帖子),并在Fi恢复DB中添加其网址。但是可能有很多图像,所以我想将它们保存在存储中的文件夹中。
所以存储路径如下所示:
/${uid}/posts/${postId}/${image1.name}
这里的postId
是我在Fi恢复中添加的新Post的文档引用Id。但是由于fi恢复不支持使用. add()
api的空文档,我必须进行一个虚拟的写入操作,只是为了获得文档ref Id(即postId)
db.collection('posts').add({isExist: true})
.then(docRef => { postDocRef = docRef; postId = docRef.id } )
现在我在存储路径中使用这个postId
,并上传图像。
上传完成后,我收到它的下载url(getDownloadURL()
),我想将其存储在FiRecoveryDB中。所以我不得不触发对同一文档的另一次写入并使用图像下载url更新它。
postDocRef.update({ url : storageDownloadUrl })
这整个过程会导致两个写操作到Fi恢复。
是否有更好的方法可以导致单次写入Fi恢复。
我想的几个选择:
您不需要“虚拟写入”来获得唯一生成的文档ID。您可以简单地使用不带参数的文档()方法生成具有唯一id的DocumentAccess,然后在数据准备就绪的一段时间后使用它写入整个文档。这些唯一ID总是在客户端上同步生成。
试试这个逻辑,它可能会在某个地方有所帮助:
final Uri uri = data.getData();
//From the onActivityResult(int requestCode, int resultCode, Intent data) method
StorageReference storageReference = YOUR_PAPER_STORAGE_REF;
// Create the file metadata
StorageMetadata metadata = new StorageMetadata.Builder()
.setContentType("application/pdf").build();
storageReference.putFile(uri, metadata)
.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
// Forward any exceptions
if (!task.isSuccessful()) {
throw Objects.requireNonNull(task.getException());
}
// Request the public download URL
return storageReference.getDownloadUrl();
}
})
.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(@NonNull Uri downloadUri) {
PaperPost mPaperPost = new PaperPost(mFirebaseUser, downloadUri.toString());
final DocumentReference mPPPostRef = mFirestore.collection("tblPapers").document().set(mPaperPost);
}
})