【问题标题】:How do I store downloadUrl of multiple images to the Firebase Firestore ? Unable to create and store inside multiple fields inside Firestore document如何将多个图像的 downloadUrl 存储到 Firebase Firestore ?无法在 Firestore 文档内的多个字段中创建和存储
【发布时间】:2020-03-16 21:26:48
【问题描述】:

这是我到目前为止所能得到的。选择图片后

selectImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUploadTask != null && mUploadTask.isInProgress()){
                    Toast.makeText(MainActivity.this, "Upload In Progress", Toast.LENGTH_SHORT).show();
                }
                else {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE);
                }
            }
        });

OnActivityResult 中,我正在将我选择的图片上传到 Firebase 存储,同时我想将这些多张图片的下载 URL 存储到 Firebase Firestore

 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     String fileName;
     final String[] downloadUrl = new String[1];
     if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
         if(data.getClipData() != null){ 

             int totalItemsSelected = data.getClipData().getItemCount();

             for(int i =0;i<totalItemsSelected;i++){

                 Uri fileUri = data.getClipData().getItemAt(i).getUri();
                 fileName = getFileName(fileUri);
                 fileNameList.add(fileName);
                 fileDoneList.add("uploading");
                 uploadListAdapter.notifyDataSetChanged();

                 final StorageReference fileToUpload = storageReference.child("Images").child(fileName);

                 final int finalI = i;
                 final int totalCount = totalItemsSelected;
                 mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                     @Override
                     public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                         fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                             @Override
                             public void onSuccess(Uri uri) {
                                 String url = String.valueOf(uri);
                                 storeLink(url,totalCount);//Method To Store the Url
                             }
                         });
                         // Toast.makeText(add_for_sale.this, "Uploading works", Toast.LENGTH_SHORT).show();
                         fileDoneList.remove(finalI);
                         fileDoneList.add(finalI,"done");

                         uploadListAdapter.notifyDataSetChanged();

                     }
                 });
                // ImageUploadInfo imageUploadInfo = new ImageUploadInfo(downloadUrl[0],fileName);


             }

             Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
         }
         else if(data.getData() != null){
             Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
         }
     }
 }


storeLink(url,totalCount) 方法中,我正在创建一个地图对象以在文档中创建字段“imageUrl”,其中“29t0Boxm0fa8UNkomuo5xPLwkx13”是一个用户ID。

private void storeLink(final String url,final int totalCount) {
    FirebaseFirestore storeUrl = FirebaseFirestore.getInstance();
    Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
    for (int i=0;i<totalCount;i++) {
        final Map<String, Object> image = new HashMap<>();
        image.put("imageUrl"+i, url);
        DocumentReference documentReference = storeUrl.collection("users").document("29t0Boxm0fa8UNkomuo5xPLwkx13");

        documentReference.set(image).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "" +
                        "OnSuccess : Image Link Saved ");
                // startActivity(new Intent(Register.this,LoginActivity.class));
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "OnFailure : " + e.toString());
            }
        });
    }
}

存储规则

  rules_version = '2'
       service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if true;
    }
  }



Firestore Rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

【问题讨论】:

    标签: java android firebase google-cloud-firestore google-cloud-storage


    【解决方案1】:
    • 确保你已经对 Map 进行了 finalString,Object> user = new HashMap();
    • 并在循环中添加 user.put("key","value")。
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final DocumentReference documentReference = db.collection("users").document("multi_image");
        final Map<String, Object> user = new HashMap<>();
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
            if (data.getClipData() != null) {
                final int totalItemsSelected = data.getClipData().getItemCount();
                for (int i = 0; i < totalItemsSelected; i++) {
                    Uri fileUri = data.getClipData().getItemAt(i).getUri();
                    final int x = i;
                    final StorageReference fileToUpload = mStorageRef.child("Images").child("" + x);
                    fileToUpload.putFile(fileUri)
                            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
                                    Task<Uri> DownloadURL = taskSnapshot.getStorage().getDownloadUrl();
                                    DownloadURL.addOnSuccessListener(new OnSuccessListener<Uri>() {
                                        @Override
                                        public void onSuccess(Uri uri) {
                                            user.put("image_" + x, uri.toString());
                                            Log.v("users", "" + user);
                                            documentReference.update(user)
                                                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                                                        @Override
                                                        public void onSuccess(Void aVoid) {
                                                            Log.v("task", "Success");
                                                        }
                                                    })
                                                    .addOnFailureListener(new OnFailureListener() {
                                                        @Override
                                                        public void onFailure(@NonNull Exception e) {
                                                            Log.v("failed", "" + e);
                                                        }
                                                    });
                                        }
                                    });
                                }
                            });
                }
                Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
            } else if (data.getData() != null) {
                Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    

    Firebase 存储 https://i.stack.imgur.com/HeYvh.png

    Firebase 数据库 https://i.stack.imgur.com/3t2aN.png

    【讨论】:

      【解决方案2】:

      这就是我最终得到的结果:

      全局创建一个ArrayList变量

      ArrayList&lt;String&gt; imageList;

      然后在里面初始化这个ArrayList

      onActivityResult as imageList = new ArrayList&lt;&gt;(totalItemsSelected); 如下代码中所述

       @Override
      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
      
          String fileName;
      
          if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
              if(data.getClipData() != null){
                  progressBar.setVisibility(View.VISIBLE);
                  final int totalItemsSelected = data.getClipData().getItemCount();
                  count = totalItemsSelected;
                  imageList = new ArrayList<>(totalItemsSelected);
      
                  StorageReference ImageFolder = FirebaseStorage.getInstance().getReference().child("ImageFolder");
      
                  for(int i =0;i<totalItemsSelected;i++){
      
                      Uri fileUri = data.getClipData().getItemAt(i).getUri();
                      fileName = getFileName(fileUri);
      
      
                      fileNameList.add(fileName);
                      fileDoneList.add("uploading");
                      uploadListAdapter.notifyDataSetChanged();
      
                      final StorageReference fileToUpload = ImageFolder.child(fileName);
                      final int finalI = i;
      
                      mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                          @Override
                          public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                              progressBar.setVisibility(View.INVISIBLE);
      
      
                              fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                  @Override
                                  public void onSuccess(Uri uri) {
                                     String url = String.valueOf(uri);
                                     imageList.add(url);
                                     // Toast.makeText(add_for_sale.this, imageList.get(finalI), Toast.LENGTH_SHORT).show();
                                     Log.i(TAG,"Added To List");
                                  }
                              });
                              fileDoneList.remove(finalI);
                              fileDoneList.add(finalI,"done");
      
                              uploadListAdapter.notifyDataSetChanged();
                          }
                      });
      
                  }
      
                  Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
              }
              else if(data.getData() != null){
                  Toast.makeText(this, "Select Two or More Images", Toast.LENGTH_SHORT).show();
              }
          }
      }
      

      现在将 URL 链接保存到 Firebase Firestore 将 ArrayList 的链接添加为 imageList.add(url;)

      并将此列表imageList 上传到 FireStore 为

      Map<String,Object> imageUrl = new HashMap<>();
                      imageUrl.put("ImageUrl", imageList);
                      String userId;
                      userId = firebaseUser.getUid();
                      firebaseFirestore.collection("ImageDetails").document(userId)
                              .set(imageUrl,SetOptions.merge());
      

      这将在您的 Firestore 文档中创建一个 ImageUrl 数组

      【讨论】:

        猜你喜欢
        • 2019-02-09
        • 1970-01-01
        • 2020-06-15
        • 2021-10-14
        • 1970-01-01
        • 2021-10-20
        • 1970-01-01
        • 2020-04-16
        • 1970-01-01
        相关资源
        最近更新 更多