我正在创建一个Android分类应用程序,并在此停留了2天,我不知道该怎么做,因为我是Firebase和android的新手。我正在尝试从相机或Firebase的存储上载图像。这是我的代码
private void executeUploadTask() {
Toast.makeText(getActivity(), "uploading image", Toast.LENGTH_SHORT).show();
final String postId = FirebaseDatabase.getInstance().getReference().push().getKey();
final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
.child("posts/users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() +
"/" + postId + "/post_image");
UploadTask uploadTask = storageReference.putBytes(mUploadBytes);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getActivity(), "Post Success", Toast.LENGTH_SHORT).show();
//insert the download url into the firebase database
Uri firebaseUri = taskSnapshot.getDownloadUrl();
Log.d(TAG, "onSuccess: firebase download url: " + firebaseUri.toString());
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Post post = new Post();
post.setImage(firebaseUri.toString());
post.setCity(mCity.getText().toString());
post.setContact_email(mContactEmail.getText().toString());
post.setCountry(mContactEmail.getText().toString());
post.setDescription(mDescription.getText().toString());
post.setPost_id(postId);
post.setPrice(mPrice.getText().toString());
post.setState_province(mStateProvince.getText().toString());
post.setTitle(mTitle.getText().toString());
post.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.child(getString(R.string.node_posts))
.child(postId)
.setValue(post);
resetFields();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getActivity(), "could not upload photo", Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double currentProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
if( currentProgress > (mProgress + 15)){
mProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
Log.d(TAG, "onProgress: upload is " + mProgress + "& done");
Toast.makeText(getActivity(), mProgress + "%", Toast.LENGTH_SHORT).show();
}
}
});
}
答案 0 :(得分:0)
不推荐使用UploadTask.getDownloadUrl()。改用StorageReference.getDownloadUrl()。