我正在观看有关 Firebase 存储的旧教程。 getDownloadUrl()
方法来自 UploadTask.TaskSnapshot
不再存在,documentation我不清楚。
到目前为止,我实现的是上传过程,我可以确认它有效,但获取 URL 很痛苦,我无法按照他们解释的方式进行操作,因为:
1) 创建 Task<Uri> urlTask = uploadTask.add[...]()
将导致在 IDE 上出现以下错误:
我不明白,因为它在文档中指定。
2) 使用 reference.getDownloadUrl()
当看到上传图像的详细信息时,将显示与控制台上显示的不同的 URL。控制台显示的下载地址是
登录时会显示
com.google.android.gms.tasks.xxx@xxxxxxx
目前我的完整代码:
if (requestCode == RC_PHOTO_PICKER) {
if (data != null) {
Toast.makeText(MainActivity.this, "Uploading...", Toast.LENGTH_SHORT).show();
Uri file = data.getData();
final StorageReference reference = mPhotoStorageReference.child(file.getLastPathSegment());
UploadTask upload = reference.putFile(file);
upload.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Image could not be uploaded: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}).addOnCompleteListener(this, new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
ChatroomMessage message = new ChatroomMessage(null, mUsername, reference.getDownloadUrl().toString()); // <- com.google.android.gms.tasks.xxx@xxxxxxx
mMessagesDatabaseReference.push().setValue(message);
Toast.makeText(MainActivity.this, "Image uploaded!", Toast.LENGTH_SHORT).show();
}
});
}
}
我的应用程序已经实现了 Firebase UI 来处理登录操作,规则是
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
最佳答案
我付出了努力并浪费了更多时间,但这是更通用和有效的解决方案
private void uploadImage() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/" +currentFirebaseUser.getUid() + "");
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Log.e("uri12",downloadUrl+"This is uri of image download");
Toast.makeText(AddItemActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AddItemActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
关于java - 如何从 Firebase 存储中检索图像的下载 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50598311/