【发布时间】:2020-10-15 19:41:40
【问题描述】:
我正在开发一个应用程序,用户可以在其中上传图像和文档。我可以分别编写用于上传图像和文档的代码,但我想要的是能够上传图像和文档,获取他们的下载 URL,同时将它们放在实时数据库中。下面的代码是用于上传图片的,我该如何更改它,以便我也可以上传文档并将下载 URL 保存在与图片相同的节点中?
final StorageReference fileReference = storageReference.child(System.currentTimeMillis() + "." + getFileExtension(resultUri));
uploadTask = fileReference.putFile(resultUri);
uploadTask.continueWithTask(new Continuation(){
@Override
public Object then(@NonNull Task task) throws Exception {
if (!task.isComplete()){
throw Objects.requireNonNull(task.getException());
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task <Uri> task) {
if (task.isSuccessful()){
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
String postid = reference.push().getKey();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("image", myUrl);
//maybe add here the url of the document
//Is it possible to upload an image and a document, get their download Urls place them in the realtime database at the same time?
//hashMap.put("document", documentUrl);
hashMap.put("publisher",FirebaseAuth.getInstance().getCurrentUser().getUid());
hashMap.put("date", mDate);
reference.child(postid).setValue(hashMap);
loader.dismiss();
startActivity(new Intent(AskAQuestionActivity.this, MainActivity.class));
finish();
}else {
String error = task.getException().toString();
Toast.makeText(AskAQuestionActivity.this, "Failed" + error, Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(AskAQuestionActivity.this, "Question could not be posted." , Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(this, "No image is selected", Toast.LENGTH_SHORT).show();
}
}
任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: java android firebase firebase-realtime-database firebase-storage