【问题标题】:Firebase getting url after image upload图片上传后Firebase获取网址
【发布时间】:2023-03-06 23:37:01
【问题描述】:

我有一个应用程序,我想上传两张图片,一张是普通图片,第二张是缩略图。我暂时忽略缩略图,只关注主图像。我正在处理的步骤如下:

第 1 步:上传图片 第 2 步:获取下载链接作为字符串 第 3 步:在 firebase 中添加下载链接到实时数据库

我卡在第 2 步 我做了以下事情:

 else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                {
                    Uri resultUri = result.getUri();

                    File thumb_filePath = new File(resultUri.getPath());
                    Bitmap thumb_bitmap = null;
                    try {
                        thumb_bitmap = new Compressor(this)
                                .setMaxWidth(200)
                                .setMaxHeight(200)
                                .setQuality(75)
                                .compressToBitmap(thumb_filePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    final byte[] thumb_byte = baos.toByteArray();

                    final StorageReference mStorageThumbPathRef = mStorageRef.child("chatappthumbimg").child(current_userid + ".jpg");
                    final StorageReference mStoragePathRef = mStorageRef.child("chatappimg").child(current_userid + ".jpg");


                    UploadTask uploadTask;
                    uploadTask = mStoragePathRef.putFile(resultUri);

                    Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                        @Override
                        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                            if (!task.isSuccessful()) {
                                throw task.getException();
                            }

                            // Continue with the task to get the download URL
                            return mStoragePathRef.getDownloadUrl();
                        }
                    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                        @Override
                        public void onComplete(@NonNull Task<Uri> task) {
                            if (task.isSuccessful()) {
                                Uri downloadUri = task.getResult();
                            } else {
                                // Handle failures
                                // ...
                            }
                        }
                    });







                }


            }

        } 

我使用文档寻求帮助:https://firebase.google.com/docs/storage/android/upload-files

但是,现在我不确定如何进行。 mStoragePathRef.getDownloadUrl();把图片的真实网址还给我? 因为在早期的一些测试中,我得到了某种任务,而不是图像 url

【问题讨论】:

  • 我不能代表 Android 方面的事情 - 我住在 Firebase 的 Web 部分......但我想他们有类似的经历。根据我的经验,你是正确的......它不会返回实际的 URL。在 JavaScript 中,它返回一个“可观察的”,最终为我们提供了 URL……我会给你一个如何获得最终 URL 的例子,但我怀疑这对你的 Android 世界会有多大帮助。
  • 谢谢@JeremyW 我很乐意看看

标签: android firebase firebase-realtime-database firebase-storage


【解决方案1】:

根据上面的 cmets,OP 要求查看我在项目中处理上传的方式 - 不幸的是,这不是 Android。我认为这不会有太大帮助,因为这不是正确的语言,但尽你所能。

具体来说,这是在 Angular 6 中使用 AngularFire2 包完成的。我包含了完整的功能供参考,但相关部分接近尾声,谈论this.downloadURLObservablethis.downloadURLSubscription$

// Uploads file to Firebase storage, and returns the file's access URL
pushUpload(pageName, upload) {
  // Returns a promise, so we can use .then() when pushUpload is called
  return new Promise( (resolve, reject) => {

    this.uploadPercent = 0;

    // Include the current timeStamp in the file name, so each upload can be uniquely identified - no 1 photo will ever be used in 2 places, can safely delete this file later w/o fear of messing up something else
    const timeStamp = new Date().getTime();

    // Upload the file
    const uploadTask = this.afStorage.upload(`${pageName}/${timeStamp}-${upload.file.name}`, upload.file);

    // Observe percentage changes
    this.uploadPercentObservable = uploadTask.percentageChanges();
    this.uploadPercentageSubscription$ = this.uploadPercentObservable.subscribe(
      eachValue => {
        this.uploadPercent = Math.round(eachValue*10) / 10
      },
      err => {
        console.log('uploadPercentageSubscription$ errored out in upload.service.ts, here is the err:')
        console.log(err)
      },
      () => {
        console.log('uploadPercentageSubscription$ completed')
      }
    )

    // Get notified when the download URL is available, return it from the function
    uploadTask.snapshotChanges().pipe( finalize( () => {
      this.downloadURLObservable = this.afStorage.ref(`${pageName}/${timeStamp}-${upload.file.name}`).getDownloadURL()
      this.downloadURLSubscription$ = this.downloadURLObservable.subscribe(
        eachValue => {
          resolve(eachValue)
        },
        err => {
          console.log('downloadURLSubscription$ errored out in upload.service..ts, here is the err:')
          console.log(err)
        },
        () => {
          console.log('downloadURLSubscription$ completed')
        }
      )
    })).subscribe()

  }); // End of returned promise
} // End of pushUpload() for regular image

【讨论】:

    【解决方案2】:

    对于任何可能被困在同一件事上的人,Uri downloadUri = task.getResult();是有真实下载地址的那个

    【讨论】:

      猜你喜欢
      • 2022-09-25
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 2013-03-28
      • 2021-01-24
      • 2020-10-15
      相关资源
      最近更新 更多