我正在尝试获取Firebase存储桶中文件的"长期持久下载链接"。我已将其权限更改为
service firebase.storage {
match /b/project-xxx.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
我的java代码看起来像这样:
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错误,并且应用程序崩溃。consol告诉我这是bc用户未登录/auth。"请在索要令牌之前登录"
问题2.我该如何解决这个问题?
请参阅文档以获取下载 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。如果您刚刚上传了一个文件,则此公共 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();
}
Firebase Storage - 易于处理上传和下载。
@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);
}
});
}
});
}
在这里我同时上传和获取图像 URL...
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();
}
});
}
对我来说,我在 Kotlin 中编写了代码,但遇到了相同的错误"getDownload()"。这是对我有用的依赖项和 Kotlin 代码。
implementation 'com.google.firebase:firebase-storage:18.1.0'
Firebase 存储依赖项
这是我添加的,它在 Kotlin 中对我有用。Storage() 将出现在 Download() 之前
profileImageUri = taskSnapshot.storage.downloadUrl.toString()
您可以将图像上传到Firestore并获取其下载URL,如下功能所示:
Future<String> uploadPic(File _image) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
var url =downloadURL.toString();
return url;
}
implementation 'com.google.firebase:firebase-storage:19.2.0'
最近从上传任务获取 url 不起作用,所以我尝试了这个并为我处理上述依赖项。所以在你使用火碱上传方法的地方使用它。filepath 是 Firebase Stoarage 的引用。
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Log.d(TAG, "onSuccess: uri= "+ uri.toString());
}
});
}
});
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
}
}
});
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());
}
}
});
}
getDownloadUrl 方法已在高于 11.0.5 的 Firebase 版本中移除我建议使用仍然使用此方法的版本 11.0.2。
getDownloadUrl 方法现已在新的 Firebase 更新中被弃用。请改用以下方法。taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
将收到的 URI 更改为 URL
val urlTask = uploadTask.continueWith { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
spcaeRef.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
//URL
val url = downloadUri!!.result
} else {
//handle failure here
}
}
您也可以执行以下操作 在最新的Firebase_storage版本中 nullsafe,
//Import
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
Future<void> _downloadLink(firebase_storage.Reference ref) async {
//Getting link make sure call await to make sure this function returned a value
final link = await ref.getDownloadURL();
await Clipboard.setData(ClipboardData(
text: link,
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Success!n Copied download URL to Clipboard!',
),
),
);
}
firebase.storage().ref( /users/${userUID}${path}/${newPostKey}
).getDownloadURL().then(url => object.imageUrl = url)
private void getDownloadUrl(){
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference imageRef = storageRef.child("image.jpg");
imageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
String profileimageurl =task.getResult().toString();
Log.e("URL",profileimageurl);
ShowPathTextView.setText(profileimageurl);
}
});
}