我正在制作一个应用程序,用户将图像上传到 Firebase 存储上。上传图像后,我想将图像的 URL 和其他详细信息上传到我自己的 API。我如何获取用户刚刚上传的图像的 Uri。 This 教程教授如何上传,但不展示如何获取图像 URL。我尝试了所有教程,但没有一个显示我想要的东西。
根据文档,可以在
.getDownloadUrl
中调用.onSuccessListener
来获取图片URL。
这是文档中的示例:
// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
});
您将在 onSuccess 回调中获取下载 URL。检查以下代码
public static void storeInFirebase(Context context, Uri uri, String type) {
StorageReference riversRef = null;
mStorageRef = FirebaseStorage.getInstance().getReference();
//to create a separate folder with all the pictures uploaded
riversRef = mStorageRef.child("pictures/" + "unique_value");
UploadTask uploadTask = riversRef.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
DialogUtils.dismissProgressDialog();
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
downloadUrl = taskSnapshot.getDownloadUrl();
Log.d("downloadUrl", "" + downloadUrl);
}
});
}
在kotlin中可以这样获取上传的图片文件url
private fun uploadImageToFirebase(fileUri: Uri) {
val user = FirebaseAuth.getInstance().currentUser
if (user != null && fileUri.toString().isNotEmpty()) {
val storage = Firebase.storage
val storageRef = storage.reference
val profilePicRef = storageRef.child("profilePictures/${user.uid}.jpg").putFile(fileUri)
profilePicRef.addOnProgressListener {
val progress = (100.0 * it.bytesTransferred) / it.totalByteCount
Log.d(TAG, "Upload is $progress% done")
}.addOnPausedListener {
Log.d(TAG, "Upload is paused")
}.addOnSuccessListener { task ->
task.storage.downloadUrl.addOnSuccessListener {
Glide.with(requireContext()).load(it).into(binding.profilePicture)
}
}
.addOnFailureListener {
Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(requireContext(), "User not authenticated", Toast.LENGTH_SHORT).show()
}
}