我正在尝试获取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.如何解决此问题?
最佳答案
请参考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()
{
@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();
}