我正在将图像上传到Firebase存储,我需要存储中的图像URL才能使用它然后将其插入FireStore中的文档中。如何在上传过程结束后获取URL而不是在完成之前?
public String uploadImage(byte[] bytes) {
try {
final StorageReference ref = storage.child("images/" + new Date().toString());
ref.putBytes(bytes)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
res = uri.toString();
return;
}
});
}
});
System.out.println("RES : " + res);
return res;
}catch (NullPointerException e){
return null;
}
}
//the variable res must return a not null value.
Ref :: Image not retrieving from Firebase
//add file on Firebase and got Download Link
filePath.putFile(imageUri).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 filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downUri = task.getResult();
Log.d(TAG, "onComplete: Url: "+ downUri.toString());
}
}
});
我们可以从taskSnapshot
获取文件的URL,如下所示:
public String uploadImage(byte[] bytes) {
try {
final StorageReference ref = storage.child("images/" + new Date().toString());
ref.putBytes(bytes)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful()) ;
Uri downloadUrl = urlTask.getResult();
}
});
System.out.println("RES : " + res);
return res;
}catch (NullPointerException e){
return null;
}
}
希望它能帮到你!