Firebase在图片上传后获取网址

时间:2018-06-12 11:42:54

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

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

第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

2 个答案:

答案 0 :(得分:1)

根据上述评论,OP要求查看我在项目中处理上传的方式 - 遗憾的是不是Android。我不认为这会有多大帮助,因为这不是正确的语言,而是从中获取任何可能的东西。

具体来说,这是使用AngularFire2包在Angular 6中完成的。我提供了完整的功能以供参考,但相关部分是最后的,讨论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

答案 1 :(得分:1)

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