Loading Image from Firebase Storage using Kotlin - android

`
Hello I'm trying to load some images from Firebase Storage using downloadUrl but it always crashes and I don't know why I already set up rules in the storage but it still doesn't work
I added these dependencies
implementation 'com.google.firebase:firebase-storage-ktx'
implementation platform('com.google.firebase:firebase-bom:31.0.2')
My code is this:
`var storageRef = Firebase.storage.reference.child("post/$uId/$fileName.png") //I want to load image from a certain user
var imageUri:String?=null
storageRef.downloadUrl.addOnSuccessListener { Uri->
imageUri=Uri.toString()
}
-.addOnFailureListener {
Toast.makeText(this#UploadActivity, it.message, Toast.LENGTH_SHORT).show()
}`
Basically when debugging it doesn't enter addOnSuccessListener nor addOnfailureLister and imageUri remains null even though I can see that downloadUrl has translated the gs://... to https://firebase...
I also added these rules indise my firebase Storage
`rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
`

The reason is that it may take time to fetch the Image from Firebase storage and before you get the Image from firebase storage you try to load the Image in ImageView and the app crashes because the Uri is still null.
Try
Firebase.storage.reference.child("post/$uId/$fileName.png").
downloadUrl.addOnSuccessListener { Uri->
Glide.with(YOUR_ACTIVITY_CONTEXT).
load(Uri.toString()).
into(YOUR_IMAGE_VIEW)
}
-.addOnFailureListener {
Toast.makeText(this#UploadActivity, it.message, Toast.LENGTH_SHORT).show()
}`
For detailed knowledge of Glide Library here is the link

Related

Flutter - FirebaseException ([firebase_storage/unknown] An unknown error occurred, please check the server response.)

I have been building an app for IOS and Android using flutter which uses firebase storage to upload files to cloud storage.I have multiple page from which i can upload files(eg:Theres a page to upload images,a seperate page tp upload pdf) but on certain pages, it throws this Exception:
Note: Page here refers to different Activity like in Android
FirebaseException ([firebase_storage/unknown] An unknown error occurred, please check the server response.)
I use same code to upload files on every page,but it throws this Exception.
When i click the upload button multiple times it will upload Sometime and most of times it fails with this Exception.
I have tried many solution including changing the security rules and adding firebase-storage#system.gserviceaccount.com as principle.
Iam using IOS Simulator for testing on IOS and physical device for android.Incase pf physical device for adroid i havnt faced any issue yet,but for simulator it throws this Exception
Here's the code i use to upload files:
uploadrepfile() async {
print("uploadiong");
final path = '${widget.uid}/Records/';
final file = File(pickedfile!.path!);
final pdfref = FirebaseStorage.instance.ref().child(path);
setState(() {
uploadTask = pdfref.putFile(file);
});
//final snapshot = await uploadTask!.whenComplete(() {});
final snapshot = await uploadTask!.whenComplete(() {});
final url = await snapshot.ref.getDownloadURL();
print(url);
FirebaseFirestore.instance
.collection("Medicalrecords")
.add({"url": url, "time": DateTime.now()});
setState(() {
uploadTask = null;
});
}
Here's my security rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
match /users/{userId}/{allPaths=**} {
allow read: if true;
allow write: if request.auth.uid == userId;
}
}
}
Any help is Appreciated

How to download image from network and use as an asset image offline in flutter

I am using sqlflite flutter package to manage a small database for my app, there is a table where I have some urls for few images from the internet , but I need to save them and use the files instead of urls to show this images later. I mean I want to do something like this :
bool internet
internet ? Image.network('the_url') : Image.assets("path to image in my assets folder")
so, is there any way to fetch images from urls and save it to be able to access it later?
You can download the image with NetworkAssetBundle and convert to Unint8List
final ByteData imageData = await NetworkAssetBundle(Uri.parse("YOUR_URL")).load("");
final Uint8List bytes = imageData.buffer.asUint8List();
Then you can load it through Image.memory() widget
Image.memory(bytes);
You can store that data in sqflite and retrive when needed
You can use the path_provider package to download from internet and save it locally. Then you can load from local asset if available. Otherwise it can download from the internet also.
Future<String?> loadPath() async {
var dir = await getApplicationDocumentsDirectory();
String dirName = widget.url!.substring(87);
file = File("${dir.path}/$dirName");
if (file.existsSync() == true && _isDownloadingPDF == false) {
// debugPrint('file.path returned');
return file.path;
} else {
return null;
}
}
Have you tried https://pub.dev/packages/cached_network_image?
It seems like this package will fulfil your requirements.

Is there a way to delete Firebase-Storage data if the whole data doesn't get uploaded?

I'm uploading multiple images to Firebase-Storage.
The problem is if i try to upload 5 images. 2/5 images gets uploaded and I kill the app the uninstall it without reopening it then the two images gets uploaded to firebase storage but the other 3 didn't. And the way I'm storing "download url" is like if all the 5 images gets uploaded then store the url with other data to Firestore and if it fails then don't store download url which means that other data won't get uploaded to Firestore.
This is the function I use to upload multiple images to database.
private fun uploadImages() {
// to store mutliple url's
val imagesUrl = ArrayList<String>()
// mUriImagesList is an arraylist of images
if (mUriImagesList.isNotEmpty()) {
for (image in mUriImagesList) {
// ref = some storage path //
val uploadTask = ref.putFile(image)
val urlTask = uploadTask.continueWithTask { task ->
if(!task.isSuccessful) {
task.exception?.let {
throw it
}
}
ref.downloadUrl
}.addOnCompleteListener { task ->
val downloadUri = task.result
imagesUrl.add(downloadUri.toString())
if(imagesUrl.size == mUriImagesList.size) {
// some other data which will uploaded to firestore if all the images get uploaded to storage
uploadMomentData(imagesUrl)
}
} else {
Log.w(NEW_FRAGMENT_TAG, "Task FAILED")
}
}
}
}
}
Is there any way to delete those 2 images from the storage if all the images failed to upload? - I thought to write a cloud function but what will be the condition? As there is no way to determine the data uploaded to Firebase-storage is not associated in anyway to firestore(by download url).

IllegalArgumentException: Firebase Storage URLs must point to an object in your Storage Bucket when trying to link a cloudinary URL to firebase

I am using Cloudiary service in order to decrease the size of an uploaded video. I am getting back a URL of a picture (which I assume is the first frame of the video) back as a response. When trying to load the video from firebase I am for some reason getting a URL and not a URI. here is my method -
private void loadVideoUri(String storageUri) {
if (StringUtils.isBlank(storageUri)) {
return;
}
// load firebase storage
Task<Uri> downloadUrlTask = FirebaseStorage.getInstance().getReferenceFromUrl(storageUri).getDownloadUrl(); // -> crash happends here
if (getContext() instanceof Activity) {
downloadUrlTask.addOnCompleteListener((Activity) getContext(), mOnDownloadUrlCompleted);
} else {
downloadUrlTask.addOnCompleteListener(mOnDownloadUrlCompleted);
}
}
here is the full error -
java.lang.IllegalArgumentException: Firebase Storage URLs must point to an object in your Storage Bucket. Please obtain a URL using the Firebase Console or getDownloadUrl().
at com.google.firebase.storage.internal.Util.normalize(com.google.firebase:firebase-storage##16.0.5:134)
at com.google.firebase.storage.FirebaseStorage.getReferenceFromUrl(com.google.firebase:firebase-storage##16.0.5:281)
at com.onemdtalent.app.ui.views.mdview.FirebasePlayerView.loadVideoUri(FirebasePlayerView.java:156)

Firebase Storage: User not permitted to access object despite public rules

I am new to Firebase storage. I made a simple app that should download a file from Firebase.
The download fails every time with the following error:
StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403
These are my rules on Firebase:
service firebase.storage {
match /b/***.appspot.com/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
I already also tried to enable anonymous authentification, but this doesn't change anything despite the login is successful.
EDIT: This is my java code:
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
mAuth.signInAnonymously().addOnCompleteListener((Activity) context, new OnCompleteListener<AuthResult>() {...}
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
//Create a storage reference from our app
storageRef = firebaseStorage.getReference();
contentDir = new File(context.getFilesDir().getAbsolutePath() + "\\content\\testfile.txt");
storageRef.getFile(contentDir).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {...}
Update:
Downloading files from the storage root is either not supported or is not covered by the default security rule. (Maybe match /{allPaths=**} doesn't include root?) Move the file to some location other than the root:
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
storageRef = firebaseStorage.getReference("anyPath");
If for testing you want to allow public access to you storage bucket, use these rules, copied from the Storage Guide. The rule posted by j_h_o_m_o is safer, limiting access to signed-in users:
// Anyone can read or write to the bucket, even non-users of your app.
service firebase.storage {
match /b/***.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Also check that your bucket name matches what you see in the Firebase Console. For example, if the Storage Files tab shows gs://project-12345.appspot.com, your rule would start:
match /b/project-12345.appspot.com/o {
NOTE: this will let anyone access your storage authenticated or not
try changing your rules to the storage to this
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth == null;
}
}
}

Categories

Resources