flutter firebase storage throwing unknown error [duplicate] - flutter

This question already has an answer here:
Firebase Storage Only showing when on certain VPN
(1 answer)
Closed 7 months ago.
edit: i notice that the code only runs till the below code and then gets out with the error. also, do note that the code provided used to work today
void pickUploadGalleryImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.gallery,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures/${fileName+getRandomString(50)}");
i am trying to upload a profile picture to firebase storage and then display it on a circular avatar. my code is as follows.
void pickUploadCameraImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.camera,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures/${fileName + getRandomString(50)}");
await ref.putFile(File(image!.path));
ref.getDownloadURL().then((value) {
print(value);
setState(() {
imageUrl = value;
});
});
}
void pickUploadGalleryImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.gallery,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures/${fileName+getRandomString(50)}");
await ref.putFile(File(image!.path));
ref.getDownloadURL().then((value) {
print(value);
setState(() {
imageUrl = value;
});
});
}
however, the terminal is throwing me with this error.
[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: [firebase_storage/unknown] An unknown error occurred, please check the server response.
i have tried to deleting the firebase storage bucket and recreating a new one but it is still giving me this error. tia for all inputs

update: turns out, i have to use a vpn where my storage is located to access the file. everything works as it should be now

Try this way.
import 'package:firebase_storage/firebase_storage.dart' as prefixStorage;
final int timestamp = DateTime.now().millisecondsSinceEpoch;
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickVideo(source:ImageSource.gallery);
final prefixStorage.Reference firebaseStorageRef = firebaseStorage
.ref()
.child('images')
.child(
'/$timestamp${image?.path.substring(image.path.indexOf('.'), image.path.length)}');
await firebaseStorageRef.putData(await image.readAsBytes());
final String? imageURL = await firebaseStorageRef.getDownloadURL();

Try giving it a child when you are uploading image to 'member_profile_pictures'.
void pickUploadCameraImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.camera,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures").child('${fileName + getRandomString(50)}');
await ref.putFile(File(image!.path));
ref.getDownloadURL().then((value) {
print(value);
setState(() {
imageUrl = value;
});
});
}
void pickUploadGalleryImage() async {
final image = await ImagePicker().pickImage(
source: ImageSource.gallery,
maxWidth: 512,
maxHeight: 512,
imageQuality: 100,
);
Reference ref = FirebaseStorage.instance
.ref()
.child("member_profile_pictures").child('${fileName + getRandomString(50)}');
await ref.putFile(File(image!.path));
ref.getDownloadURL().then((value) {
print(value);
setState(() {
imageUrl = value;
});
});
}

Im also in Singapore and facing firebase storage upload issue from this morning (yesterday still no issue), our own system haven't update anything.

Related

How can I upload mutiple-photo in flutter app via ImgePicker

I want to add the function which can upload multiple Photo image via ImagePicker
In this code, I can just upload single photo, not mutiple.
This app operating by flutter, dart and firebase server.
[Code]
void dispose() {
textEditingController.dispose();
super.dispose();
}
File _image;
Future _getImage() async {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
maxWidth: 1000,
maxHeight: 1000,
);
setState(() {
_image = image;
});
}
Future _uploadFile(BuildContext context) async {
if (_image != null) {
final firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('post')
.child('${DateTime.now().millisecondsSinceEpoch}.png');
final task = firebaseStorageRef.putFile(
_image,
StorageMetadata(contentType: 'image/png'),
);
final storageTaskSnapshot = await task.onComplete;
final downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
await Firestore.instance.collection('post').add(
{
'contents': textEditingController.text,
'displayName': widget.user.displayName,
'email': widget.user.email,
'photoUrl': downloadUrl,
'userPhotoUrl': widget.user.photoUrl,
});
}
final images = await _picker.pickMultiImage(
maxHeight: 1024,
maxWidth: 1024,
imageQuality: 50,
);
I created here 3 functions used to pick files from imagePicker and to upload them to firebase storage.
first, pick images from gallery:
final imageFiles = await pickImages();
second, upload the images:
final path = 'path/where/you/want/to/save/your/images';
final imageUrls = uploadImages(imagesFiles, path)
print(imageUrls);
you can now use the images urls to save to firestore
Future<List<File>> pickeImages() async {
ImagePicker picker = ImagePicker();
final images = await picker.pickMultiImage(
maxHeight: 1000, maxWidth: 1000, imageQuality: 90);
List<File> files = [];
if (images == null || images.isEmpty) return [];
for (var i = 0; i < images.length; i++) {
final file = File(images[i].path);
files.add(file);
}
return files;
}
Future<String?> _uploadImageFile(File file, String path) async {
try {
final storage = FirebaseStorage.instance;
TaskSnapshot? taskSnapshot;
final storageRef = storage.ref().child(path);
final uploadTask = storageRef.putFile(file);
taskSnapshot = await uploadTask.whenComplete(() {});
final imageUrl = await taskSnapshot.ref.getDownloadURL();
return imageUrl;
} catch (e) {
throw Exception(e.toString());
}
}
Future<List<String>> uploadImages(
List<File> files,
String path,
) async {
final urls = <String>[];
try {
if (files.isNotEmpty) {
for (var i = 0; i < files.length; i++) {
final file = files[i];
final imagePath = '$path/${Random().nextInt(10000)}.jpg';
final url = await _uploadImageFile(file, imagePath);
urls.add(url!);
}
}
return urls;
} on FirebaseException {
rethrow;
}
}
Instead of using ImagePicker.pickImage, use ImagePicker.pickMultiImage. That gives you a List instead of an XFile. Then you can just upload all images in the list. For instance, add an image parameter to your _uploadFile Function so that its function signature is
Future _uploadFile(BuildContext context, XFile image)
and just upload all images like
for (final image of images) {
_uploadFile(context, image)
}

upload image by flutter in firebase Storage

I try to upload an image on firebase storage and get the error.
Future selectImage(ImageSource source) async {
try {
XFile? xImage = await ImagePicker().pickImage(source: source);//getting picture from phone
if(xImage == null ) return 'there is no image';
final File file = File(xImage.path);
//final Image image = Image.file(File(xImage.path));
print(xImage.path);
Directory appDocDir = await getApplicationDocumentsDirectory();
String filePath = '${appDocDir.absolute}/file-to-upload.png';
print(filePath);
final storageRef = FirebaseStorage.instance.ref().child("UsersProfilePhoto/");
await storageRef.putFile(file);
} on FirebaseException catch (e) {
print(e.message);
}
}
Try like this.
Future selectImage(ImageSource source) async {
try {
ImagePicker imagePicker = ImagePicker();
XFile pickedFile = await imagePicker.pickImage(source: source, imageQuality: 80);
File imageFile = File(pickedFile.path);
if(imageFile == null ) return 'there is no image';
print(imageFile.path);
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
final storageRef = FirebaseStorage.instance.ref().child("UsersProfilePhoto/");
await storageRef.putFile(imageFile);
} on FirebaseException catch (e) {
print(e.message);
}
}
Try this
import 'package:path/path.dart' as Path1;//for storing image path in firestore
DatabaseReference reference = FirebaseDatabase.instance.reference();
FirebaseStorage storage = FirebaseStorage.instance;
File? fileImage;
//call this function for picking image
pickedImage() async{
PickedFile? file = await ImagePicker().getImage(
source: ImageSource.camera,
maxHeight: 1000,
maxWidth: 1000
);
File image = file!.path;
setState((){
fileImage = image;
});
}
//call this function for storing image in firestore
_storeImage() async{
Reference storagerefrence = storage.ref().child('card_images/${Path1.basename(fileImage!.path)}');
TaskSnapshot uploadTask = await storagerefrence.putFile(fileImage!);
String url = await storagerefrence.getDownloadURL();//download url from firestore and add to firebase database
reference.child("image").push().set({
'image' : url
});
}

Flutter rebuilds widget without waiting for code execution

I have a function to upload image to the server. However the widgets starts rebuilding while the image is being uploaded and does not execute code after image is uploaded.
InkWell(
child: Icon(
Icons.camera,
size: 50,
color: Colors.red[400],
),
onTap: () {
_imageFile =
_picker.getImage(source: ImageSource.camera);
_imageFile.then((file) async {
if (file != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
});
},
)
This is the output on the console from print statements
I/flutter (10171): Calling build Method
I/Timeline(10171): Timeline: Activity_launch_request time:68831133
I/flutter (10171): Uploading image to server
I/flutter (10171): Calling build Method
I/flutter (10171): Image uploaded successfully
As can be seen above no other code is executed and the widget has rebuilt itself. What am I possibly doing wrong?
_imageFile = _picker.getImage(source: ImageSource.camera);
its not right, getImage is an Asynchronous function so you need to wait for it to finish.
do this - _imageFile = await _picker.getImage(source: ImageSource.camera);
If you want to use then do it like this,
_picker.getImage(source: ImageSource.camera).then((image)...your code...)
That's because when you're using _imageFile = _picker.getImage(source: ImageSource.camera); the _imageFile result will come in the future and your next code is executed.
You can fixed the problem either using await:
onTap: () async {
_imageFile =
await _picker.getImage(source: ImageSource.camera);
if (_imageFile != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
},
Or keep using then with a slight change:
onTap: () {
_picker.getImage(source: ImageSource.camera)
.then((file) async {
if (file != null) {
fileName = file.path.toString();
var res = await Auth.uploadImage(file);
print("Response for image upload is : ");
print(res);
await setUserData();
}
});
},
See explanation about await & then: Async/Await/then in Dart/Flutter

How to copy the path of image and store it in? Error:- The method copy isnt defined fo type 'PickedFile'

This is the error when using the copy function. How do I save the image clicked from the camera?
Future _takePicture() async {
final imageFile = await ImagePicker().getImage(
source: ImageSource.camera,
maxHeight: 600,
);
setState(() {
_storedImage = File(imageFile.path);
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appDir.path}/$fileName');
}
you should copy _storedImage instead of imageFile
imageFile type is PickedFile and hasn't copy method
Future _takePicture() async {
final imageFile = await ImagePicker().getImage(
source: ImageSource.camera,
maxHeight: 600,
);
setState(() {
_storedImage = File(imageFile.path);
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await _storedImage.copy('${appDir.path}/$fileName');
}

Converting of Image File created using image_picker package of flutter to AssetImage/Image.asset?

I am new to flutter, i am building an app where i need to convert the file(image) generated after using image_picker package to asset image to use in the app.
example code as follows, which creates file(Image)
final Function onSelectImage;
ImageInput(this.onSelectImage);
File _storedImage;
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.camera,
maxWidth: 600,
);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = imageFile;
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
Thanks in advance
You can create an image variable which you can rever to and update when you selected the image.
See the following code:
final Function onSelectImage;
ImageInput(this.onSelectImage);
File _storedImage;
Image _tempImage;
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.camera,
maxWidth: 600,
);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = imageFile;
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
setState(() {
_tempImage = imageFile;
});
}
#override
Widget build(BuildContext context) {
return _tempImage == null ? Container(child:null) : Image(image: _tempImage);
}