Not able to upload file to firebase storage in Flutter - flutter

i'm trying to do the upload of image files to the cloud firestore in firebase using flutter. i'm always getting the following error and I do not understand where the issue is.
FirebaseException ([firebase_storage/object-not-found] No object exists at the desired reference.)
console:
E/StorageException(10183): StorageException has occurred.
E/StorageException(10183): Object does not exist at location.
E/StorageException(10183): Code: -13010 HttpResult: 404
Here is my code:
class DatabaseMethods {
CollectionReference cartesPro =
FirebaseFirestore.instance.collection('cartesPro');
FirebaseStorage storage = FirebaseStorage.instance;
Future<String> uploadFile(file) async {
Reference reference = storage.ref().child('cartesPro/');
print('REFERENCE: ${reference}');
UploadTask uploadTask = reference.putFile(file);
print('UPLOAD TASK${uploadTask.snapshot}');
TaskSnapshot taskSnapshot = await uploadTask;
return await taskSnapshot.ref.getDownloadURL();
}
void addFile(CartPro cartPro) {
cartesPro.add({
"cartUserId": cartPro.cartUserId,
"cartTimestamp": FieldValue.serverTimestamp()
});
}
}
Log of reference and uploadTask snapshot:
I/flutter (10183): REFERENCE: Reference(app: [DEFAULT], fullPath: cartesPro)
I/flutter (10183): UPLOAD TASK: TaskSnapshot(ref: Reference(app: [DEFAULT], fullPath: cartesPro), state: TaskState.running)
Everything seems pretty fine to me but still I do always get that error!
I'd be grateful for any kind of help!

First, make sure your firebase storage rules are correct.
Example:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Second, try pushing the data that comes as File as Uint8List.
Example:
Future<String> uploadFile(File file, String uid) async {
Reference reference = storage.ref().child('cartesPro/').child(uid); //It's helpful to name your file uniquely
Uint8List bytes = file.readAsBytesSync(); //THIS LINE
var snapshot = await reference.putData(bytes); //THIS LINE
return await snapshot.ref.getDownloadURL();
}

Related

firebase_storage/object-not-found No object exists at the desired reference

my code
Future<String> uploadFile(File _image) async {
int uploadTimestamp = DateTime.now().millisecondsSinceEpoch;
Reference ref = FirebaseStorage.instance.ref().child('posts/$uploadTimestamp');
UploadTask uploadTask = ref.putFile(_image);
final TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() {});
final url = await taskSnapshot.ref.getDownloadURL();
return url;
}
firebase_storage: ^10.3.1
firebase_core: ^1.19.1
Error: [firebase_storage/object-not-found] No object exists at the desired reference.
what are you trying to achieve. one suspeect here is youre not calling _image anywhere. Seem like youre trying to upload an int.
You are not calling the
await ref.putFile(_image);
before the:
final TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() {});
And then call:
await ref.getDownloadURL();
after the upload in order to get the download url.
and also try to listen to the different upload states like:
uploadTask.snapshotEvents.listen((TaskSnapshot taskSnapshot) {
switch (taskSnapshot.state) {
case TaskState.running:
final progress =
100.0 * (taskSnapshot.bytesTransferred / taskSnapshot.totalBytes);
print("Upload is $progress% complete.");
break;
case TaskState.paused:
print("Upload is paused.");
break;
case TaskState.canceled:
print("Upload was canceled");
break;
case TaskState.error:
// Handle unsuccessful uploads
break;
case TaskState.success:
// Handle successful uploads on complete
// ...
break;
}
});
This could be useful. I put in together this.
Future<String> uploadImageToDefaultBucket(File image) async {
Reference firebaseStorageRef = FirebaseStorage.instance.ref("your-ref").child("your-path");
UploadTask uploadTask = firebaseStorageRef.putFile(image);
TaskSnapshot taskSnapshot = await uploadTask;
return taskSnapshot.ref.getDownloadURL();
}
The error message you provided is generally caused by an incorrect Cloud Storage bucket URL. The image you would like to retrieve cannot be located in your Cloud Storage. You should first check that the bucket URL and file name are correctly spelled.
Additionally, this is how you add the image extension.
basically this error shows because you don't have started your storage at firebase console, you should first go to storage and press get started, then set your rules for test mode in case you are using for testing and after that full restart your app, hope it works for you.
firebase_storage/object-not-found No object exists at the desired
reference

flutter: [firebase_storage/unknown] An unknown error occurred, please check the server response

From an IOS simulator, I am suppose to see "success" as the response after selecting avatar image, typing username, email, password, and bio description
. However I kept getting this error response, like this: " [firebase_storage/unknown] An unknown error occurred, please check the server response."
[Update] I was able to solve this by editing Firebase Storage rules by omitting ": if false" to this :
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Just change the .putfile to .putdata this will fix this error also check the storage rules.
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(source: ImageSource.gallery);
imgFile = File(image!.path);
UploadTask uploadTask;
Reference ref = FirebaseStorage.instance.ref().child('books').child('/hogehoge.jpg');
try {
uploadTask = ref.putData(await imgFile.readAsBytes());
imgUrl = await (await uploadTask).ref.getDownloadURL();
} catch (e) {
print(e.toString());
}

Unhandled Exception: PlatformException(download_error, Object does not exist at location., null, null), but my Object does exists at the location

I m trying to upload the image on firebase, using this code:
Future<String> uploadCourseImage(filePath, courseName) async{
File file = File(filePath);
var timestamp = Timestamp.now().millisecondsSinceEpoch;
FirebaseStorage _storage = FirebaseStorage.instance;
try{
await _storage.ref().child('courseImage/${this.TeacherName}/$courseName$timestamp').putFile(file);
}on Exception catch(e){
print(e.hashCode);
}
String downloadURL = await _storage.ref().child('courseImage/${this.TeacherName}/$courseName$timestamp').getDownloadURL();
this.courseURL =downloadURL;
notifyListeners();
return downloadURL;
}
But I get this error:
Unhandled Exception: PlatformException(download_error, Object does not exist at location., null, null), but my Object does exists at the location
Using UploadTask class object helps in uploading the file I think.
Try this method for uploading image to Firebase Storage and extracting url after uploading is done.
Future uploadImage(BuildContext context) async {
FirebaseStorage storage = FirebaseStorage.instance;
String? email = FirebaseAuth.instance.currentUser!.email!;
Reference ref =
storage.ref().child('users/${email + DateTime.now().toString()}/Profile Image: ${DateTime.now().toString()}');
UploadTask uploadTask = ref.putFile(_image!);
final TaskSnapshot downloadUrl = (await uploadTask);
imageUrl = await downloadUrl.ref.getDownloadURL();
}
The below code worked fro me:
//Create a reference to the location you want to upload to in firebase
StorageReference reference =
storage.ref().child('courseImage/${this.TeacherName}/$courseName$timestamp');
//Upload the file to firebase
StorageUploadTask uploadTask = reference.putFile(image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
// Waits till the file is uploaded then stores the download url
String url = await taskSnapshot.ref.getDownloadURL();

Flutter web - Uploading image to firebase storage

I am using the firebase_storage: ^8.0.6 package on flutter web. I want to upload image to firebase storage that I get using FilePicker package.
The problem is that the new package uses the putFile() method to upload files. But File from dart:io doesn't work on flutter web and it also doesn't accept the File object from dart:html.
I can upload image as Blob using the putBlob() method but then it doesn't upload it as image type but it's type is application/octet-stream. I don't want to upload the image file as a blob.
Future<String> uploadImage(PlatformFile file) async {
try {
TaskSnapshot upload = await FirebaseStorage.instance
.ref(
'events/${file.name}-${DateTime.now().toIso8601String()}.${file.extension}')
.putBlob(Blob(file.bytes));
String url = await upload.ref.getDownloadURL();
return url;
} catch (e) {
print('error in uploading image for : ${e.toString()}');
return ';
}
}
How to fix this issue?
You can use the putData() method to send the image and set it's metadata as a image.
Future<String> uploadImage(PlatformFile file) async {
try {
TaskSnapshot upload = await FirebaseStorage.instance
.ref(
'events/${file.path}-${DateTime.now().toIso8601String()}.${file.extension}')
.putData(
file.bytes,
SettableMetadata(contentType: 'image/${file.extension}'),
);
String url = await upload.ref.getDownloadURL();
return url;
} catch (e) {
print('error in uploading image for : ${e.toString()}');
return '';
}
}
putData() method takes Uint8List by default.
Uploading images using TaskSnapshot is not working on my flutter web project.
I used firebase_storage: ^8.1.3 .
Following code is working for my web project.
String nameImage = DateTime.now().millisecondsSinceEpoch.toString();
Reference _reference = FirebaseStorage.instance
.ref()
.child('images/$nameImage.png}');
await _reference
.putData(
await image.readAsBytes(),
SettableMetadata(contentType: 'image/jpeg'),
)
.whenComplete(() async {
await _reference.getDownloadURL().then((value) {
user.profilePictureURL = value;
FireStoreUtils.firestore
.collection(USERS)
.doc(user.userID)
.update({'profilePictureURL': user.profilePictureURL});
});
});
You can still use .putFile when you use the File.fromUri() constructor and get the Uri from the PlatformFile object using Uri.dataFromBytes and passing the bytes to it.
The code below contains changes that should remove the error:
TaskSnapshot upload = await FirebaseStorage.instance
.ref(
'events/${file.name}-${DateTime.now().toIso8601String()}.${file.extension}')
.putFile(File.fromUri(Uri.dataFromBytes(file.bytes.toList())));

getDownloadURL returns null when uploadTask is complete but uploads image to storage

The image I am trying to upload to storage is successful, however when I want to use that image that was uploaded to store the URL into the database, it returns null for some reason.
Future<String> _uploadPic(String docRef, File file) {
FirebaseStorage _storage = FirebaseStorage.instance;
auth.currentUser().then((userID) async{
StorageReference reference = _storage.ref().child(userID).child(docRef);
StorageUploadTask uploadTask = reference.putFile(file);
String downloadURL = (await uploadTask.onComplete).ref.getDownloadURL().toString();
return downloadURL;
});
}
Log:
I/flutter (17507): debug: the uri is: null
Future<dynamic> _uploadPic(String docRef, File file) {
FirebaseStorage _storage = FirebaseStorage.instance;
// you need to return the result...
return auth.currentUser().then((userID) async {
StorageReference reference = _storage.ref().child(userID).child(docRef);
StorageUploadTask uploadTask = reference.putFile(file);
return (await uploadTask.onComplete).ref.getDownloadURL();
});
}
The getDownloadURL() method returns a Future. So if you call toString() on that, you get the string representation of the future, and not a download URL. Instead you'll want to wait for the getDownloadURL() future to also complete, and that will give you the URL.
String downloadURL = (await (await uploadTask.onComplete).ref.getDownloadURL()).toString();