How to upload a image url downloaded from firebase storage to firestore document for newly registered user? - flutter

I have made it till uploading the image to firebase storage and download the url.Here, I need to store the newly registered user information in an Firestore document. I am storing some details one of those is the image URL downloaded from firebase storage.
Now, I need to assign the downloaded Url to Firestore to access it in my dart pages.
uploadImage() async {
var random = Random(25);
final StorageReference fireref = FirebaseStorage.instance
.ref()
.child('profilepics/${random.nextInt(5000).toString()}.jpg');
StorageUploadTask task = fireref.putFile(profilepic);
StorageTaskSnapshot snapshottask = await task.onComplete;
String downloadUrl = await snapshottask.ref.getDownloadURL();
if (downloadUrl != null) {
userManagement.addProfilePic(downloadUrl.toString()).then((val) {
Navigator.of(context).pushReplacementNamed('/twelf');
});
}
}
The above is the code of getting the image url from firebase storage.And, If you can see I have called a method addProfilePic to add the downloaded URL to firestore. And the method is,
Future addProfilePic(picUrl) async {
//---
}
What Should i write in this method to upload url to firestore. I am not able to understand.
Additional code for understanding:
class UserManagement {
storeNewUser(user, context) {
Firestore.instance.collection('/userdetails').add({
'Email': user.email,
'uid': user.uid,
'displayName': user.fullname,
'photoUrl': user.photoUrl
}).then((value) {
Navigator.of(context).pop();
Navigator.of(context).pushReplacementNamed('/selectpic');
}).catchError((e) {
print(e);
});
}
And the below code is near registration the final code that upload data to firestore:
final String userId = await widget.auth
.createUserWithEmailAndPassword(_email, _password)
.then((signedInUser) async {
var userUpdateInfo = new UserUpdateInfo();
userUpdateInfo.displayName = _fullname;
userUpdateInfo.photoUrl = _imageurl;
//'https://cdn.mos.cms.futurecdn.net/QjuZKXnkLQgsYsL98uhL9X-1024-80.jpg';
final user = await FirebaseAuth.instance.currentUser();
user.updateProfile(userUpdateInfo).then((user) {
FirebaseAuth.instance
.currentUser()
.then(
(user) => {UserManagement().storeNewUser(user, context)})
.catchError((e) {
print(e);
});
}).catchError((e) {
print(e);
});
}).catchError((e) {
print(e);
});
print('Registered user: $userId');
}

Try this:
Future<String> uploadImage(profilepic) async {
StorageUploadTask uploadTask = storageRef.child("profilepics/${random.nextInt(5000).toString()}.jpg").putFile(profilepic);
StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
String downlaodUrl = await storageTaskSnapshot.ref.getDownloadURL();
return downlaodUrl;
}
// String imageUrl = await uploadImage(profilepic); You can store the value of imageUrl in firebase document.
Firestore.instance.collection('/userdetails').add({
// All fields you want to have in a document
'photoUrl': imageUrl; // use the image url variable
});
/// To update a currentUser document
Firestore.instance.collection('/userdetails')
.document(your_user_document_name_here)
.updateData({
// All fields you want to update in a document
'photoUrl': imageUrl; // use the image url variable
});

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

uploading multiple xfiles to firebase storage

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.

Can't get a proper URL when Image from Storage Firebase is linked to CloudFirestore

I cant get a valid URL to retrieve in my method when images are linked to CloudFirestore from Storage in Firebase:
Future uploadImage(BuildContext context) async {
String fileName = basename(_imageFile.path);
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('ifprofile/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(_imageFile);
TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() {
var firebaseUser = FirebaseAuth.instance.currentUser;
FirebaseFirestore.instance.collection('/userProfile').add({
"imageUrl": _imageFile.path,
});
FirebaseFirestore.instance
.collection('/influencerUser')
.doc(firebaseUser.uid)
.update({
// All fields you want to update in a document
'imageUrl': IfUserProfile.imageUrl,
});
// Finish to Link images to Cloud Firestore
});
taskSnapshot.ref
.getDownloadURL()
.then((value) => print("Image uploaded: $value"));
}
into cloud firestore I get URL like this:
/data/user/0/it.test.testapp/cache/image_picker5217031945896769637.jpg
any input please?
try to modify ur code a but like this
final url = await taskSnapshot.ref
.getDownloadURL();
then take that url and put it in your firestore db
here is some code
final storageRef = FirebaseStorage.instance.ref('$folderName/$imagename');
final uploadTaskSnapshot = await storageRef.put(image).future;
final imageUri = await uploadTaskSnapshot.ref.getDownloadURL();

How to upload image on cloud firestore linked to an entry?

I am trying to upload image on cloud firestore. But there is a error I am not able to catch.
I am using the code under uploadFile from here
Future<void> getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
widget._image = image;
print("added image");
});
uploadImage();
}
Future uploadImage() async {
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = reference.putFile(widget._image);
StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {
widget.photourl = downloadUrl;
}, onError: (err) {
print('Error');
});
}
'added image' prints on the terminal, so there isn't a problem in that it seems.
photourl is null, but it should contain the url.
Thank you.
In the above code, you are just getting an image URL from Firebase storage. You need to update the photoURL in Firestore also.
Future<void> updateOneField = database
.collection('entries')
.document('D3idV9o7uWT4pWvby643')
.updateData(
{
"photourl": downloadUrl
});
It seems the problem was because of state of widget. This solved it
Future uploadImage() async {
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = reference.putFile(widget._image);
StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {
setState(() {
widget.photourl = downloadUrl;
});
}, onError: (err) {
print('Error');
});
}

Save Image Url in Cloud FireStore

I try to create details of product in Cloud FireStore. Create document and save image in storage is all works. Mu issue is image url doesn't save in document.
dart file
class ProductService {
Firestore _firestore = Firestore.instance;
void createProduct(_nameproductController, _priceproductController,
_currentCategory, url) async {
_firestore.collection("products").document().setData({
'name': _nameproductController,
'price': _priceproductController,
'category': _currentCategory,
'image': url,
});
}
}
upload image
void uploadImg() async {
var timekey = DateTime.now();
fb.StorageReference storageReference =
fb.storage().ref('imgProduct/${timekey.toString()}.jpg');
fb.UploadTaskSnapshot uploadTask = await storageReference
.put(_image1, fb.UploadMetadata(contentType: 'image/jpg'))
.future;
var imageUrl = await uploadTask.ref.getDownloadURL();
url = imageUrl.toString();
print('Image Url' + url);}
submit button
RaisedButton(
onPressed: () async {
if (_formKeyProduct.currentState.validate()) {
uploadImg();
ProductService().addProduct(
_nameproductController.text,
_priceproductController.text,
_currentCategory.categoryname.toString(),
url,
);
_formKeyProduct.currentState.reset();
_nameproductController.clear();
_priceproductController.clear();
}
setState(() {
_currentCategory = null;
});
},
you need to await uploadImg();