I am trying to upload a image using the code below:
Future<String> uploadImageToFirebase(File imageFile) async {
String fileName = basename(imageFile.path);
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('uploads/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(imageFile);
var taskSnapshot = await uploadTask;
String imageUrl = "";
await taskSnapshot.ref.getDownloadURL().then(
(value) {
// print("Upload Image Completed: $value");
imageUrl = value;
},
);
return imageUrl;
}
But I get the following error:
E/StorageException(15399): Caused by: java.io.IOException: { "error": { "code": 400, "message": "Your bucket has not been set up properly for Firebase Storage. Please visit 'https://console.firebase.google.com/project/imgs-e4332/storage/files' to automatically repair this issue and then retry. If the issue lasts longer than five minutes, you may have insufficient permissions to repair the project. You can check your permissions by visiting 'https://console.firebase.google.com/iam-admin/iam/project?project=imgs-e4332'." }}
Related
hope all is well.
I have been trying to upload an image or file to firebase storage from flutter web. Once I try to call put data the console just reads
Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)
I don't know how to check server response when using a plugin but this error comes from the try-catch block with on firebaseexception print error
Code: XFile? pickedImage;
_startFilePicker() async {
pickedImage = await ImagePicker().pickImage(
source: ImageSource.camera,
imageQuality: 60,
maxWidth: 250,
);
setState(() {
_hasUploaded = true;
});
uploadImageToStorage(pickedImage);
}
String uploadedPhotoUrl = '';
uploadImageToStorage(XFile? pickedFile) async {
try {
final String url = FirebaseStorage.instance.bucket;
Reference _reference = FirebaseStorage.instance
.refFromURL(
'gs://genderbasedviolence-bd860.appspot.com/') //${FirebaseAuth.instance.currentUser!.uid}
.child('images');
final bytes = await pickedFile!.readAsBytes();
await _reference.putData(bytes);
} on FirebaseException catch (e) {
print(e.code);
}
}
Please let me know if you need more info. Thanks
Important: I found the same question but it is closed with incomplete debugging information.
I am uploading an image to firebase storage and then getting the download URL of that image and storing it to firebase so I can use that URL to show the User's profile image using network image.
It was working fine before when I was storing the image like
Reference storageRef = FirebaseStorage.instance.ref('images');
file = await _compressImage(file: file,);
await storageRef.putFile(file);
final String downloadUrl = await storageRef.child(id).getDownloadURL();
return downloadUrl;
but after I am storing images in specific folders
Reference storageRef = FirebaseStorage.instance.ref('images');
file = await _compressImage(file: file, id: id);
await storageRef
.child(Get.find<UserController>().user.username)
.child(id)
.putFile(file);
final String downloadUrl = await storageRef.child(id).getDownloadURL();
return downloadUrl;
it is showing this error.
[firebase_storage/object-not-found] No object exists at the desired reference.
Here is the explainable code:
I am storing downloadable URL in newImage variable
String newImage;
if (_controller.file != null) {
newImage = await Database().uploadFile(
file: _controller.file,
id: Get.find<UserController>().user.username);
print("new image: " + newImage.toString());
}
But here when I am printing newImage's value it is printing null to console.
new image: null
Here is the second method to upload image to firebase storage.
Future<String> uploadFile({#required File file, #required String id}) async {
try {
file = await _compressImage(file: file, id: id);
await storageRef
.child(Get.find<UserController>().user.username)
.child(id)
.putFile(file);
final String downloadUrl = await storageRef.child(id).getDownloadURL();
return downloadUrl;
} catch (e) {
print(e);
}
}
Debug Console:
E/StorageException(11376): StorageException has occurred.
E/StorageException(11376): Object does not exist at location.
E/StorageException(11376): Code: -13010 HttpResult: 404
E/StorageException(11376): { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
E/StorageException(11376): java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
E/StorageException(11376): at com.google.firebase.storage.network.NetworkRequest.parseResponse(NetworkRequest.java:434)
E/StorageException(11376): at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(NetworkRequest.java:451)
E/StorageException(11376): at com.google.firebase.storage.network.NetworkRequest.processResponseStream(NetworkRequest.java:442)
E/StorageException(11376): at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:272)
E/StorageException(11376): at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:286)
E/StorageException(11376): at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:70)
E/StorageException(11376): at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:62)
E/StorageException(11376): at com.google.firebase.storage.GetDownloadUrlTask.run(GetDownloadUrlTask.java:76)
E/StorageException(11376): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
E/StorageException(11376): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
E/StorageException(11376): at java.lang.Thread.run(Thread.java:764)
I/flutter (11376): [firebase_storage/object-not-found] No object exists at the desired reference.
I/flutter (11376): new image: null
But when I check the firebase storage and the image is uploaded successfully there.
What I know is that image is successfully uploading to firebase storage but the above method somehow returning a downable URL before uploading the image.
What worked for me was a bit unexpected.
First, I had the code like this which is how many examples have it.
Reference reference = storage.ref(filePath);
UploadTask uploadTask = reference.putFile(imageToUpload);
final storageSnapshot = uploadTask.snapshot;
final downloadUrl = await storageSnapshot.ref.getDownloadURL();
Then, I decided to play around with it.
I notice if I await the putFile call, it changes the return type, even though its not a future.
Reference reference = storage.ref(filePath);
final TaskSnapshot snapshot = await reference.putFile(imageToUpload);
final downloadUrl = await snapshot.ref.getDownloadURL();
And what do you know, this worked! Very odd, considering it's not obvious you can await the putFile call.
I lost many hours with the same problem as you and IDK why but it is working by creating the reference before using it:
final FirebaseStorage feedStorage =
FirebaseStorage.instanceFor(bucket: F.feedBucket);
Reference refFeedBucket = feedStorage
.ref()
.child('venues')
.child(auth.user.uid)
.child('vibes')
.child(p.basename(file.path));
String downloadUrl;
TaskSnapshot uploadedFile = await refFeedBucket.putFile(file);
if (uploadedFile.state == TaskState.success) {
downloadUrl = await refFeedBucket.getDownloadURL();
}
return downloadUrl;
here's how we do it
Reference ref = FirebaseStorage.instance
.ref()
.child('user_Image')
.child('${authResult.user?.uid}.jpg');
UploadTask uploadTask = ref.putFile(imageUser);
final snapshot = await uploadTask.whenComplete(() => null);
final urlImageUser = await snapshot.ref.getDownloadURL();
Try this
for loading image from firebase
Future<String> downloadedUrl(String imageName) async {
String downloadedUrl =
await storage.ref('$imageName').getDownloadURL();
return downloadedUrl;
}
In my case, I got the capitalization of words case wrong on my path.
The Firebase storage is Case sensitive
check it, please!
What I want to do: Upload a file and a video with Firebase Storage 0.5.0 and return url.
What current problem is: I can upload file and image with Firebase storage 0.5.0, but I can't return url. I also see my file and video uploaded in Firebase storage in Firebase console.
My code:
Future<String> _uploadFile(Reference ref, File file,
[SettableMetadata metadata]) async {
UploadTask uploadTask = ref.putFile(file, metadata);
uploadTask.whenComplete(() async {
try {} catch (onError) {
print("Error");
}
});
final url = await ref.getDownloadURL();
return url;
}
Future<String> uploadVideo(File video,
{String refName, SettableMetadata metadata}) async {
metadata = SettableMetadata(contentType: 'video/mp4');
final name = refName != null ? refName : path.basename(video.path);
final ref = _VideoRef.child(name);
return _uploadFile(ref, video, metadata);
}
Future<File> downloadImage(String imageUrl, String savePath) async {
final ref = _storage.ref(imageUrl);
var file = File(savePath);
await ref.writeToFile(file);
return file;
}
What the console told me:
FirebaseException (Firebase_storage/object-not-found). No object exist in desired reference.
How do I fix this?
Try the following:
uploadTask.whenComplete(() async {
try {
url = await ref.getDownloadURL();
} catch (onError) {
print("Error");
}
});
When the future completes, call getDownloadURL() to get the url.
I use this code to upload picture to firebase Firestore. The uploading code is fine. But what if the user cancels the upload in the middle of the uploading process. Because Android user actually have the Back Button, right. Once they click it, the uploading process should be canceled. Once they do that, I received some kind of error message. How do I solve it?
Future<bool> uploadToFirebase(
File image,
String path,
String tag,
String number,
) async {
// get userID
final FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseUser user = await _auth.currentUser();
String userID = user.uid;
// get timeStamp
var datetime = DateTime.now();
var timeStamp = '${datetime.millisecondsSinceEpoch}';
// set tag; currently undefined
// tag = tag != null ? tag : 'notag';
print('ID: ${user.uid}');
final StorageReference firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('$path/${userID}_${timeStamp}_${number}_${tag}.jpg');
final StorageUploadTask uploadTask = firebaseStorageRef.putFile(image);
print('uploadTask : $uploadTask');
final StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
print('uploadTask : ${uploadTask.isSuccessful}');
print('taskSnapshot : ${taskSnapshot.storageMetadata}');
if (uploadTask.isComplete) {
var downloadUrl = await taskSnapshot.ref.getDownloadURL();
var filename = await taskSnapshot.ref.getName();
var filelocation = await taskSnapshot.ref.getPath();
var bucket = await taskSnapshot.ref.getBucket();
var token = downloadUrl.toString().split('=media&token=')[1];
print('name: $filename');
print('path_firebase: $filelocation');
print('downloadUrl: $downloadUrl');
print('bucket: $bucket');
print('token : $token');
await User_DatabaseService().imageData(
title: filename, // Not sure what exactly is a title
filename: filename,
token: token,
filelocation: filelocation,
url: downloadUrl,
created: 'created',
creator_uid: userID,
format: 'jpg',
created_date: datetime,
timestamp: timeStamp,
tag_label: tag,
user_tag: 'user_tag',
rating: 0,
like: 0,
display_count: 0,
participants: [],
post_notification: false,
score: 0,
);
return true;
} else {
return false;
}
}
Error message
Exception has occurred.
FlutterError (setState() called after dispose(): _UploadPictureInfoState#65d68(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().)
am trying to send an image that I take from phone to Firebase storage. the first function gets the image with the image picker plugin and passing the path return in as argument for the upload function.the image uploads to cloud storage but however in the panel the type is application/octet-stream and the image does not show
String download_path;
var imageFile;
picker() async{
File theImage = await ImagePicker.pickImage(
source: ImageSource.gallery);
imageFile = theImage;
var theimagepath = theImage.path;
setState(() {
imageFile = theImage;
});
}
Future<Null> uploadFile(String myfilepath)async{
final RegExp regExp = RegExp('([^?/]*\.(jpg))');
final filename = regExp.stringMatch(myfilepath);
final Directory tempDir = Directory.systemTemp;
final File thefile = await File('${tempDir.path}/$filename').create();
final StorageReference sref = FirebaseStorage.instance.ref().child('storeFolderName').child(filename);
final StorageUploadTask uploadTask = sref.putFile(thefile);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
download_path = downloadUrl.toString();
print('download url printed : $download_path');
}
IconButton(
icon: Icon(Icons.cloud_done),
onPressed: (){uploadFile(imageFile.toString());
},
),
log output:
D/Surface (18601): Surface::setBufferCount(this=0x9272d800,bufferCount=4)
D/GraphicBuffer(18601): register, handle(0x97ee29c0) (w:480 h:854 s:480 f:0x1 u:f02)
D/GraphicBuffer(18601): register, handle(0x97ee2e40) (w:480 h:854 s:480 f:0x1 u:f02)
D/GraphicBuffer(18601): register, handle(0x8ea20140) (w:480 h:854 s:480 f:0x1 u:f02)
W/System (18601): ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
I/System.out(18601): e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
I/System.out(18601): [OkHttp] sendRequest<<
D/GraphicBuffer(18601): register, handle(0x8ea21040) (w:480 h:854 s:480 f:0x1 u:f02)
W/System (18601): ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
I/System.out(18601): e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
I/System.out(18601): [OkHttp] sendRequest<<
I/flutter (18601): download url printed : https://firebasestorage.googleapis.com/v0/b/cloud-fs-demo.appspot.com/o/storeFolderName%2FIMG_20180711_080138.jpg?alt=media&token=6fb05871-04df-458d-93bc-1951cd122770
E/[EGL-ERROR](18601): __egl_platform_cancel_buffers:644: surface->num_buffers(4)
It doesn't really make sense to me that if you have the file why send the path to the file? What seems to be the error is that it doesn't find the location of the file. Instead, I would do something like this:
String download_path;
var imageFile;
picker() async{
File theImage = await ImagePicker.pickImage(
source: ImageSource.gallery);
imageFile = theImage;
var theimagepath = theImage.path;
setState(() {
imageFile = theImage;
});
}
Future<Null> uploadFile(File myFile)async{
final StorageReference sref =
FirebaseStorage.instance.ref().child('storeFolderName').child(myFile.toString());
final StorageUploadTask uploadTask = sref.putFile(myFile);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
download_path = downloadUrl.toString();
print('download url printed : $download_path');
}
IconButton(
icon: Icon(Icons.cloud_done),
onPressed: (){uploadFile(imageFile);
},
),
I have the same issue. The auto detect mime type doesn't seems to work, so I end up using the mime package and sending the mime type in StorageMetadata.
I also face this issue and after two days finally solve this by adding metaData, contentType. What interesting that in my case the same code work for android but was wrong for iOS.
so here is a code snippet which I use:
final File selectedImage = await ImagePicker.pickImage(
source: ImageSource.gallery,
);
filePath = selectedImage.path;
currentFile = selectedImage;
final StorageReference storageRef =
FirebaseStorage.instance.ref().child('images');
final StorageUploadTask task = storageRef.child('myImage.jpeg').putFile(selectedImage, StorageMetadata(contentType: 'image/jpeg'));
await task.onComplete; // do something
So without StorageMetadata of putFile method the images is uploading as application/octet-stream (only on iOS). But with metaData work just fine for me. Hope that was helpful.