提问者:小点点

在Firebase存储中添加映像并在Fi恢复中引用,同时避免在Fi恢复中重复写入


我想在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恢复。

我想的几个选择:

  1. 我自己在本地生成postId,这也将充当文档Id。[Firebase存储是否为文件提供唯一ID?
  2. 不要在存储路径中使用postId,而是生成唯一的image.name
  3. Fi恢复考虑提供对空文档的引用,就像实时DB[相当于Fi恢复中的. push?

共2个答案

匿名用户

您不需要“虚拟写入”来获得唯一生成的文档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);
                }
            })