如何从Firebase存储getDownloadURL获取URL

Jon*_*ger 12 java android firebase firebase-storage

我正在努力获取Firebase存储桶中文件的"长期持久下载链接".我已将此权限更改为

service firebase.storage {
  match /b/project-xxx.appspot.com/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我的javacode看起来像这样:

private String niceLink (String date){
    String link;
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    link = dateRef.getDownloadUrl().toString();
    return link;
}
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到的uri链接看起来像 com.google.android.gms.tasks.zzh@xxx

问题1.我可以从此获得类似的下载链接:https://firebasestorage.googleapis.com/v0/b/project-xxxx.appspot.com/o/20-5-2016.csv?val = media&token = b5d45a7f-3ab7-4f9b-b661-3a2187adxxxx

当我尝试获取上面的链接时,我在返回之前更改了最后一行,如下所示:

private String niceLink (String date){
    String link;
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    link = dateRef.getDownloadUrl().getResult().toString();
    return link;
}
Run Code Online (Sandbox Code Playgroud)

但是当这样做时我得到403错误,并且应用程序崩溃.consol告诉我这是bc用户未登录/ auth."在请求令牌之前请先登录"

问题2.我该如何解决这个问题?

Ben*_*lfe 16

当您调用时getDownloadUrl(),该调用是异步的,您必须订阅成功回调以获取结果:

// Calls the server to securely obtain an unguessable download Url
private void getUrlAsync (String date){
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
    {
        @Override
        public void onSuccess(Uri downloadUrl) 
        {                
           //do something with downloadurl
        } 
    });
}
Run Code Online (Sandbox Code Playgroud)

这将返回一个公共的不可思议的下载URL.如果你刚上传了一个文件,那么这个公共网址将在上传的成功回调中(你上传后不需要调用另一个异步方法).

但是,如果你想要的String只是参考的表示,你可以打电话.toString()

// Returns a Uri of the form gs://bucket/path that can be used
// in future calls to getReferenceFromUrl to perform additional
// actions
private String niceRefLink (String date){
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    return dateRef.toString();
}
Run Code Online (Sandbox Code Playgroud)


Sub*_*der 7

//Firebase 存储 - 易于上传和下载。

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == RC_SIGN_IN){
        if(resultCode == RESULT_OK){
            Toast.makeText(this,"Signed in!", LENGTH_SHORT).show();
        } else if(resultCode == RESULT_CANCELED){
            Toast.makeText(this,"Signed in canceled!", LENGTH_SHORT).show();
            finish();
        }
    } else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){

        // HERE I CALLED THAT METHOD
        uploadPhotoInFirebase(data);

    }
}

private void uploadPhotoInFirebase(@Nullable Intent data) {
    Uri selectedImageUri = data.getData();

    // Get a reference to store file at chat_photos/<FILENAME>
    final StorageReference photoRef = mChatPhotoStorageReference
                    .child(selectedImageUri
                    .getLastPathSegment());

    // Upload file to Firebase Storage
    photoRef.putFile(selectedImageUri)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    // Download file From Firebase Storage
                    photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri downloadPhotoUrl) {
                            //Now play with downloadPhotoUrl
                            //Store data into Firebase Realtime Database
                            FriendlyMessage friendlyMessage = new FriendlyMessage
                                    (null, mUsername, downloadPhotoUrl.toString());
                            mDatabaseReference.push().setValue(friendlyMessage);
                        }
                    });
                }
            });
}
Run Code Online (Sandbox Code Playgroud)


Shr*_*kur 6

在这里我正在上传并同时获取图像网址...

           final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");

            if (uriProfileImage != null) {

            profileImageRef.putFile(uriProfileImage)
                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                               // profileImageUrl taskSnapshot.getDownloadUrl().toString(); //this is depreciated

                          //this is the new way to do it
                   profileImageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Uri> task) {
                                       String profileImageUrl=task.getResult().toString();
                                        Log.i("URL",profileImageUrl);
                                    }
                                });
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(ProfileActivity.this, "aaa "+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
            }
Run Code Online (Sandbox Code Playgroud)