uploading multiple xfiles to firebase storage - flutter

I am trying to upload multiple (max 5) xfiles images (image_picker library) to firebase storage. currently, it uploads only one with the below method:
Future<void> addProduct({
BuildContext? ctx,
String? proName,
String? productDescription,
double? count,
double? price,
required List<XFile> images
}) async {
try {
var imageUrls = await Future.wait(images.map((_image) =>
uploadFile(_image)));
await firestore
.collection(outletsCollection)
.doc(_currentUserOutletId)
.set({
products: FieldValue.arrayUnion([
{
productId: Uuid().v4(),
productName: proName,
prodDesc: productDescription,
countInStock: count,
productPrice: price,
productImg: FieldValue.arrayUnion([imageUrls]),
}
]),
});
} catch (err) {
String errMsg = "error blahblah";
errorDialog(ctx!, errMsg);
}
notifyListeners();
}
for the uploadFile method i tried using images.forEach() instead of .map(), but it gave me void type error. uploadFile method:
Future<String> uploadFile(XFile _image) async {
var storageReference = storage
.ref()
.child('product_images')
.child(_currentUserOutletId!)
.child(Uuid().v4());
final metadata = SettableMetadata(
contentType: 'image/jpeg',
customMetadata: {'picked-file-path': _image.path},
);
if (kIsWeb) {
await storageReference.putData(await _image.readAsBytes(), metadata);
} else {
await storageReference.putFile(io.File(_image.path), metadata);
}
return await storageReference.getDownloadURL();
}
so, at the end only one image is uploaded and addProduct() does not add product to firestore database. log in android studio returns nothing. I couldn't find a method that would work with the xfile. help appreciated very much!

List<XFile> _imageFileList;
try{
final pickedFile = await _picker.pickMultiImage();
setState(() {
_imageFileList = pickedFile;
_imageFileList.forEach((element) async {
firebase_storage.FirebaseStorage storage = firebase_storage.FirebaseStorage.instance;
var date = DateTime.now().millisecondsSinceEpoch;
try {
setState(() {
_loading = true;
});
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance.ref('uploads/photos/'+date.toString()+'_image.png').putData(await element.readAsBytes(), SettableMetadata(contentType: 'image/jpeg'));
await storage.ref('uploads/file-to-upload.png').putData(await element.readAsBytes(), SettableMetadata(contentType: 'image/jpeg'));
firebase_storage.TaskSnapshot downloadUrl = (await task);
String url = (await downloadUrl.ref.getDownloadURL());
// print(url.toString());
} on FirebaseException catch (e) {
// e.g, e.code == 'canceled'
setState(() {
_loading = false;
});
}
});
try this way using image_picker plugin. You can get url after image upload and you have yo it in your data.

Related

How can I show first time that getting image from firebase storage in my app?

I define pick image and photoUrl variables:
File? image;
String? photoUrl;
This is my pick image method:
Future pickImage(ImageSource source) async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final imageTemporary = File(image.path);
setState(() {
this.image = imageTemporary;
});
} on PlatformException catch (e) {
print('Failed to pick image : $e');
}
}
This is my upload image function ı upload image with current user ids:
Future uploadFile() async {
final path = '${_auth.currentUser!.uid}.jpg';
final file = File(image!.path);
final ref = FirebaseStorage.instance
.ref()
.child('images/${_auth.currentUser!.uid}.jpg');
task = await ref.putFile(file);
//final url = await ref.getDownloadURL();
//print('Download URLLLLLLLLLLLLLLLLLLLLL : $url');
/*
I saved download image url to setstate method
setState(() {
photoUrl = url.toString();
});
*/
}
This is my download image and init state method, when I upload image to firebase storage first time, ı am getting no object exist at desired reference error, but after ı upload image then I try
to download image and I want to show in image.network it works, How can I fix this error when I try to upload and download first time without error ?
Future downloadImage() async {
final ref = FirebaseStorage.instance
.ref()
.child('images/${_auth.currentUser!.uid}.jpg');
final url = await ref.getDownloadURL();
print('Download URLLLLLLLLLLLLLLLLLLLLL : $url');
setState(() {
photoUrl = url.toString();
});
}
#override
initState() {
// TODO: implement initState
super.initState();
downloadImage();
}
This is my error:
and
this is my storage its empty :
The problem seems to be that you are trying to get the url before uploading the image, Here is what you can do :
uploadImage() async {
final _firebaseStorage = FirebaseStorage.instance;
final _imagePicker = ImagePicker();
PickedFile image;
//Check Permissions
await Permission.photos.request();
var permissionStatus = await Permission.photos.status;
if (permissionStatus.isGranted){
//Select Image
image = await _imagePicker.getImage(source: ImageSource.gallery);
var file = File(image.path);
if (image != null){
//Upload to Firebase
var snapshot = await _firebaseStorage.ref()
.child('images/imageName')
.putFile(file).onComplete;
var downloadUrl = await snapshot.ref.getDownloadURL();
setState(() {
imageUrl = downloadUrl;
// in here you can add your code to store the url in firebase database for example:
FirebaseDatabase.instance
.ref('users/$userId/imageUrl')
.set(imageUrl)
.then((_) {
// Data saved successfully!
})
.catchError((error) {
// The write failed...
});
});
} else {
print('No Image Path Received');
}
} else {
print('Permission not granted. Try Again with permission access');
}
source How to upload to Firebase Storage with Flutter
I hope this will be helpfull

Image URL from firebase storage to firestore

this is how I upload images to firebase storage and get the Download URL in firebase Firestore. Everything works properly how ever I get the 1st URL but not the Second one.
Future<void> uploadImage2(image2) async {
setState(() {
isLoader2 = true;
});
final bytess = image2.readAsBytesSync();
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'CarImage');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('Toyota-Images/$timeStamp/2.png')
.putData(bytess, metadata);
firebase_storage.TaskSnapshot downloadUrl2 = (await task);
String url = (await downloadUrl2.ref
.getDownloadURL()); //this is the url of uploaded image
imageUrl2 = url;
setState(() {
isLoader2 = false;
});
}
Future<void> uploadImage3(image3) async {
setState(() {
isLoader3 = true;
});
final bytess = image3.readAsBytesSync();
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'CarImage');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('Toyota-Images/$timeStamp.png')
.putData(bytess, metadata);
firebase_storage.TaskSnapshot downloadUrl3 = (await task);
String url = (await downloadUrl3.ref
.getDownloadURL()); //this is the url of uploaded image
imageUrl3 = url;
setState(() {
isLoader3 = false;
});
}
You can upload image to firebase as below
First of all you need to add this plugin in pubspec.yaml
firebase_storage: ^8.0.0
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
Future<void> uploadFile(File _image) async {
setState(() {
isLoader = true;
});
final bytess = _image.readAsBytesSync(); //"_image" is your selected image or any other which you need to upload
var timeStamp = DateTime.now();
final metadata = firebase_storage.SettableMetadata(contentType: 'image/jpeg');
firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance
.ref('cover_photo/'+timeStamp.toString()+'insp_cover_photo.png').putData(bytess,metadata);
firebase_storage.TaskSnapshot downloadUrl = (await task);
String url = (await downloadUrl.ref.getDownloadURL()); //this is the url of uploaded image
setState(() {
isLoader = false;
});
}
Let me know if you have any questions
You can do it using firebase_storage.
you can get url by using this function.
Future<String> uploadFile(File _imageFile) async {
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
Reference reference = FirebaseStorage.instance.ref().child(fileName);
UploadTask uploadTask = reference.putFile(_imageFile);
return uploadTask.then((TaskSnapshot storageTaskSnapshot) {
return storageTaskSnapshot.ref.getDownloadURL();
}, onError: (e) {
throw Exception(e.toString());
});
}

Reading data from Cloud Storage using Flutter web

I am using a flutter web application (.dart), the aim is to read data from the Cloud Storage. I tried this but I keep getting null.
loadFromStorage() async {
print("Calling cloud function...");
final ref = FirebaseStorage.instance.ref().child('/data/ecg/hp2-1B72D3/1584859928685.ecg').getData(100).then((data) =>
setState(() {
imageBytes = data.toString();
})
);
print(imageBytes);
}
what is it that I am doing wrong?
Hi this is the method i use on web with package firebase
Future<String> uploadImage(
{#required Uint8List imageData, #required String productId}) async {
// print('FirebaseImageStorageRepositoryWeb.uploadImage() started');
StorageReference ref = firebase.storage().ref('Products').child(productId);
String imageUrl;
await ref.put(imageData).future.whenComplete(() async {
await ref.getDownloadURL().then((url) {
imageUrl = url.toString();
// print('image url is :$imageUrl');
return;
}).catchError((e) {
// print('FirebaseImageStorageRepositoryWeb.uploadImage() error: $e');
});
return;
});
return imageUrl;
}
#override
Future deleteImage({#required String productId}) async {
StorageReference ref = firebase.storage().ref('Products').child(productId);
ref.delete().whenComplete(() {
return;
}).catchError((e) {
print('FirebaseImageStorageRepositoryWeb.deleteImage() error: $e');
});
return;
}
And this is the device verision usin firebase_storage
final picker = ImagePicker();
Future<String> uploadImage(
{#required Uint8List imageData, #required String productId}) async {
// print('FirebaseImageStorageRepositoryDevice.uploadImage() started');
String imageUrl;
await ref.child('Products').child(productId).putData(imageData).onComplete.whenComplete(() async {
// print('FirebaseImageStorageRepositoryDevice.uploadImage() image uploaded');
await ref.child('Products').child(productId).getDownloadURL().then((url) {
// print('FirebaseImageStorageRepositoryDevice.uploadImage() getting imageUrl');
imageUrl = url;
// print('image url is :$imageUrl');
return;
}).catchError((e) {
// print('FirebaseImageStorageRepositoryDevice.uploadImage() error: $e');
});
return;
});
return imageUrl;
}
This should put you in the right direction

Flutter async/await is not working between 2 Firebase functions

I'm trying to call a cloud firestore function that has to persist an object only when another function returns the url of the file in Firebase Storage but the async await is not working and the second function is called anyway whereas the first function is not yet completed!!!
await schoolProfileProvider.uploadSchoolProfileAvatar(data).then( (data) {
schoolProfileProvider.addSchoolProfile(data);
});
print('PROFILE ADDED');
Future<SchoolProfileData> uploadSchoolProfileAvatar(SchoolProfileData data) async {
List<File> avatars = [];
data.childrenDetails.forEach((child) {
avatars.add(File(child.childImage));
});
try {
await _api.uploadFilesToStorage(avatars, 'image', 'png').then((urls) {
for (var i = 0; i < urls.length; i++) {
data.childrenDetails[i].childImage = urls[i];
print('ADD ' + data.childrenDetails[i].childImage);
}
});
} on Exception catch (e) {
print(e.toString());
}
return data;
}
T cast<T>(x) => x is T ? x : null;
Future<List<String>> uploadFilesToStorage(List<File> files, String type, String extension) async {
final urls = <Future<String>>[];
files.forEach((file) async {
StorageReference storageRef = storage.ref().child(file.path);
final StorageTaskSnapshot downloadUrl =
(await storageRef
.putFile(file, StorageMetadata(contentType: type + '/' + extension))
.onComplete);
await downloadUrl.ref.getDownloadURL().then((url) {
urls.add(cast<Future<String>>(url));
print('URL for file ${file.path} = ${url.toString()}');
});
});
print ('urls returned');
return Future.wait(urls);
}
Future addSchoolProfile(SchoolProfileData data) async{
var result;
try {
result = await _api.addDocument(data.toJson());
} on Exception catch(e) {
print (e.toString());
}
return result;
}
I've managed to make the things work and execute addSchoolProfile only after uploadFilesToStorage is completed by reducing the nested functions and making the await downloadUrl.ref.getDownloadURL() as the last instruction returned in the callee function.
Please find the code for who is interested in :
The caller :
schoolProfileProvider.addSchoolProfileAndUploadAvatar(data);
Future addSchoolProfileAndUploadAvatar(SchoolProfileData data) async {
List<File> avatars = [];
data.childrenDetails.forEach((child) {
avatars.add(File(child.childImage));
});
try {
for (int i=0;i<avatars.length;i++){
await _api.uploadFileToStorageAndGetUrl(avatars[i], 'image', 'png').then((url) {
print('URL for file ${avatars[i].path} = ${url.toString()}');
data.childrenDetails[i].childImage = url;
print('ADD ' + data.childrenDetails[i].childImage);
});
}
_api.addDocument(data.toJson()) ; // Add document in Google Firebase after setting the avatar url
} on Exception catch (e) {
print(e.toString());
}
}
The callee :
Future <String> uploadFileToStorageAndGetUrl(File file,String type, String extension) async{
StorageReference storageRef = storage.ref().child(file.path);
final StorageTaskSnapshot downloadUrl =
(await storageRef
.putFile(file, StorageMetadata(contentType: type + '/' + extension))
.onComplete);
return await downloadUrl.ref.getDownloadURL(); // return the url of the file in Google Storage
}

Async function doesn't await

I'm trying to upload an image to firebase storage but when I called the function, await is not executed to get the url. What am I missing in this?
Looking at this other topic I've got that the problem may be the "then", but how can I set the code to await the url?
Async/Await/then in Dart/Flutter
Future < String > uploadImage(File imageFile) async {
String _imageUrl;
StorageReference ref =
FirebaseStorage.instance.ref().child(firebaseUser.uid.toString());
await(ref.putFile(imageFile).onComplete.then((val) {
val.ref.getDownloadURL().then((val) {
_imageUrl = val;
print(val);
print("urlupload");
});
}));
print(_imageUrl);
print("urlnoupload");
return _imageUrl;
}
Thanks!
you had async/await when you didn't need it because you were capturing value in the then function
Future<String> uploadImage(File imageFile) async {
String _imageUrl;
StorageReference ref = FirebaseStorage.instance.ref().child(firebaseUser.uid.toString());
return ref.putFile(imageFile).onComplete.then((val) {
return val.ref.getDownloadURL()
}).then((_imageUrl) {
return _imageUrl;
});
},