如何从Firebase存储getDownloadURL获取URL

问题描述 投票:12回答:5

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

service firebase.storage {
  match /b/project-xxx.appspot.com/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

我的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;
}

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

问题1.我可以从此获得类似的下载链接:https://firebasestorage.googleapis.com/v0/b/project-xxxx.appspot.com/o/20-5-2016.csv?alt=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;
}

但是当这样做时我得到403错误,并且应用程序崩溃了。控制台告诉我这是bc用户未登录/ auth。 “在请求令牌之前请先登录”

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

java android firebase firebase-storage
5个回答
16
投票

请参考documentation for getting a download URL

当你调用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
        } 
    });
}

这将返回一个公共的不可思议的下载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();
}

1
投票

// Firebase easy和工作上传和下载。

@覆盖

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);
                        }
                    });
                }
            });
}

0
投票
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();

final   StorageReference fileupload=mStorageRef.child("Photos").child(fileUri.getLastPathSegment());
UploadTask uploadTask = fileupload.putFile(fileUri);

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();
        }
        return ref.getDownloadUrl();

    }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                Uri downloadUri = task.getResult();
                Picasso.get().load(downloadUri.toString()).into(image);

            } else {
                 // Handle failures
            }
       }
});

0
投票

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

           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();
                            }
                        });
            }

0
投票
Clean And Simple
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key) {
        storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
                new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {
                            task.getResult().getMetadata().getReference().getDownloadUrl()
                                    .addOnCompleteListener(MainActivity.this, 
                                            new OnCompleteListener<Uri>() {
                                @Override
                                public void onComplete(@NonNull Task<Uri> task) {
                                    if (task.isSuccessful()) {
                                        FriendlyMessage friendlyMessage =
                                                new FriendlyMessage(null, mUsername, mPhotoUrl,
                                                        task.getResult().toString());
                                        mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
                                                .setValue(friendlyMessage);
                                    }
                                }
                            });
                        } else {
                            Log.w(TAG, "Image upload task was not successful.",
                                    task.getException());
                        }
                    }
                });
    }

0
投票

在大于11.0.5的firebase版本中删除了getDownloadUrl方法。我建议使用仍然使用此方法的版本11.0.2。


0
投票

对我来说,我在Kotlin中完成了我的代码,我遇到了同样的错误“getDownload()”。以下是对我有用的依赖项和Kotlin代码。

implementation 'com.google.firebase:firebase-storage:18.1.0' firebase存储依赖项

这是我添加的,它在Kotlin中为我工作。 Storage()将在Download()之前出现

profileImageUri = taskSnapshot.storage.downloadUrl.toString()

0
投票

getDownloadUrl方法现已在新的firebase更新中折旧。而是使用以下方法。 taskSnapshot.getMetadata()。getReference()。getDownloadUrl()。的toString()

© www.soinside.com 2019 - 2024. All rights reserved.