我试图将个人资料图片上传到Firebase存储,然后将其下载URL保存到数据库。上传效果完美,但下载网址遇到问题。我已经尝试了Stack Overflow上的几乎所有内容。我正在分享相关代码。
<div *ngFor="let queestion of questionsList; let i=index; ">
<label>
{{question.id}}
<input type="radio" [name]='i+1'>
<span>Yes</span>
<input type="radio" [name]='i+1' >
<span>No</span><br>
</label>
</div>
<div style="text-align: center">
<button type="button">All Yes</button>
<button type="button">All No</button>
<button type="button">Submit</button>
<button type="button">Clear</button>
</div>
选择图像
private String user_Name, user_Email, user_Password, user_Age, user_Phone, imageUri;
Uri imagePath;
上传数据
userProfilePic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*"); //Specify the type of intent
intent.setAction(Intent.ACTION_GET_CONTENT); //What action needs to be performed.
startActivityForResult(Intent.createChooser(intent, "Select Image"),
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { //Here we get the result from startActivityForResult().
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null){
imagePath = data.getData(); //data.getData() holds the path of the file.
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath); //this converts the Uri to an image.
userProfilePic.setImageBitmap(bitmap);
imageTrue = 1;
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
答案 0 :(得分:1)
您的代码正确。您只需要在 sendUserData()函数中的代码内部进行一些更正。您将在 UploadTask
的onSuccess
中获得imageUrl
DatabaseReference myRef;
private void sendUserData (){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
myRef = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
final StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
//Here the root storage reference of our app storage is is "storageReference".
//.child(firebaseAuth.getUid()) creates a folder for every user. .child("images")
//creates another subfolder Images and the last child() function
//.child("Profile Pic") always gives the name of the file.
//User id/Images/profile_pic.png
//We can follow the same process for all other file types.
if(imageTrue==1){
UploadTask uploadTask = imageReference.putFile(imagePath); //Now we need to upload the file.
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "File Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
imageUri = downloadUri.toString();
saveUserDetails(imageUri); // Image uploaded
}
});
Toast.makeText(getApplicationContext(), "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}else{
saveUserDetails(""); // Image not uploaded
}
}
saveUserDetails
的常用功能:
public void saveUserDetails(String imageUri){
UserProfile userProfile = new UserProfile(user_Name, user_Age, user_Email, user_Phone, imageUri);
myRef.setValue(userProfile);
Toast.makeText(getApplicationContext(), "User Data Sent.", Toast.LENGTH_SHORT).show();
}
答案 1 :(得分:1)
根据Firebase official Documentation,您可以使用UploadTask
方法上的addOnCompleteListener
下载URl。
UploadTask uploadTask =null;
final StorageReference ref = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic").child(imagePath);
uploadTask = ref.putFile(file);
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();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
saveUserDetails(uri);
} else {
// Handle failures
// ...
}
}
});
另一种替代方法,在成功上传图片后,使用get downloadUrl.hope查询并获取图片网址,这可能会对您有所帮助!
private void getImageUrl(){
storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic").child(imagePath).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
saveUserDetails(uri);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
}