一尘不染

如何从Firebase Storage获取URL getDownloadURL

java

我正在尝试获取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错误,应用崩溃了。控制台告诉我这是不列颠哥伦比亚省用户未登录/ auth。“请在请求令牌之前登录”

问题2.如何解决此问题?


阅读 586

收藏
2020-02-25

共1个答案

一尘不染

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

这将返回一个公开的,不可猜测的下载网址。如果你只是上传文件,则此公共网址将位于上传的成功回调中(上传后,你无需调用其他异步方法)。

但是,如果你只想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();
}
2020-02-25