我要将图像上传到Firebase存储,我需要存储中的图像URL才能使用它,然后将其插入FireStore中的文档中。 如何在上传过程完成之后而不是在完成之前获取网址?
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.
答案 0 :(得分:0)
我们可以从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;
}
}
希望对您有帮助!
答案 1 :(得分:0)
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());
}
}
});