Firebase Storage upload picture from gallery Flutter (No error) - firebase

I want to upload a picture choosen from gallery to Firestore Storage, this is my first time but I read docs and took a look on the internet, this is what I wrote (it works without errors but doing nothing on the storage).
Code below, I tested imgFromGallery and it works maybe the problem are Storage functions.
Future<File> imgFromGallery() async {
try {
final ImagePicker _picker = ImagePicker();
final PickedFile imageFile =
await _picker.getImage(source: ImageSource.gallery, imageQuality: 50);
//If there is no image selected, return.
if (imageFile == null) return null;
//File created.
File tmpFile = File(imageFile.path);
//it gives path to a directory - path_provider package.
final appDir = await getApplicationDocumentsDirectory();
//filename - returns last part after the separator - path package.
final fileName = tmpFile.path.split('/').last;
//copy the file to the specified directory and return File instance.
return tmpFile = await tmpFile.copy('${appDir.path}/$fileName');
} catch (e) {
print(e);
return null;
}
}
//Save file to Storage function
Future<void> setPicture(String pathStorage) async {
try {
final File file = await imgFromGallery();
if (file == null) return;
FirebaseStorage.instance.ref(pathStorage).putFile(file);
return;
} catch (e) {
print(e);
}
}
P.S. : I would like to return the URL of the uploaded picture as return of "setPicture" but I still don't know how to do this.

You are just few steps away!
TaskSnapshot task = await FirebaseStorage.instance.ref(pathStorage).putFile(file);
After successful upload, you will get TaskSnapshot. That has a reference member ref.
String image_url = await task.ref.getDownloadURL();
This image_url is the URL of the uploaded picture.
ref: What is the the method to use onComplete function to add Images to Firebase Storage

Related

Flutter Web: Images uploaded to firebase storage not showing preview

I am migrating one of my apps to the web with flutter for the first time. My app uses firebase packages to post images to firebase storage. We know "file path" doesn't work on the web so I had to change to byte. But on the firebase storage, I discovered that the images posted through bytes cannot be previewed. If you click on the token, rather than a preview, it will just download straight away.
Here is a pictorial illustration of what I mean:
Images, when clicked are supposed to be able to show a preview like this
But this is what I get
I see they are uploaded as documents instead of file.
Please how do I rectify this.
This is my code below
Future selectFile() async {
final result = await FilePicker.platform.pickFiles(allowMultiple: false, type: FileType.image);
if (result == null) return;
final path = result.files.single;
setState(() => imageFile = path);
}
//upload
Future upload() async {
if (imageFile == null) return;
final fileName = imageFile!.name;
final destination = 'FTV/Thumbnails/$fileName';
// task = FirebaseApi.uploadFile(destination, file!);
task = FirebaseApi.uploadBytes(destination, fileBytes!);
setState(() {});
if (task == null) return;
final snapshot = await task!.whenComplete(() {});
var urlDownload = await snapshot.ref.getDownloadURL();
// print('Download-Link: $urlDownload');
setState(() {
imageURL = urlDownload;
});
}

How to add multiple images in flutter (firebase)

how I can add multiple images and store them in an array in firebase ?
every container has a + button so the user can add single image per container then I WANT TO STORE them in my firebase
any help would be greatly appreciated ^^
what you are showing in your image is fbCloudStore which is use to store information in json structure.
To store the images you may use fbStorge.
here's an snippet I use on my project:
Future<String?> uploadFile({
required FilePickerResult file,
required String fileName,
required FirebaseReferenceType referenceType,
}) async {
try {
final ref = _getReference(referenceType);
final extension = path.extension(file.files.first.name);
final _ref = ref.child(fileName + extension);
late UploadTask uploadTask;
if (kIsWeb) {
uploadTask = _ref.putData(file.files.first.bytes!);
} else {
uploadTask = _ref.putFile(File(file.files.single.path!));
}
var url;
await uploadTask.whenComplete(
() async => url = await uploadTask.snapshot.ref.getDownloadURL());
print(url);
return url;
} on FirebaseException catch (_) {
print(_);
}
}
Note that I'm returning the URL of fbStorage in order to associate it with fbCloudStorage
final url =
await FirebaseStorageSer.to.uploadFile(
file: result,
fileName: STORAGE_USER_PROFILE_PICTURE,
referenceType: FirebaseReferenceType.user,
);
if (url != null) {
await FirebaseAuthSer.to
.updateUserProfile(photoUrl: url);
}
FirebaseReferenceType.user is just a simple enum to simplify ref targets.

My function not working even if it meets the condition flutter

I have tried to add a function that allow the user to add a profile picture inside my app.
late String? profileURL = '';
late File userProfilePicture;
...
Future pickAndUploadImage() async {
final ImagePicker _picker = ImagePicker();
try {
XFile? image = (await _picker.pickImage(source: ImageSource.gallery));
print('eee');
await new Future.delayed(const Duration(seconds: 2));
userProfilePicture = File(image!.path);
print(userProfilePicture);
print(File(image.path));
if (userProfilePicture != File(image.path)) {
print('It didnt work sorry');
Navigator.pop(context);
}
else {
print('Should be startting to put file in');
var snapshot = await storage
.ref()
.child('userProfiles/$userEmail profile')
.putFile(userProfilePicture);
print('file put in!');
profileURL = await snapshot.ref.getDownloadURL();
}
setState(() {
DatabaseServices(uid: loggedInUser.uid).updateUserPhoto(profileURL!);
print(profileURL);
});
} catch (e) {
print(e);
}
}
The thing is, this line : if (userProfilePicture != File(image.path)) seen not to work. I do not know why, but here is my output :
> flutter: eee
>flutter: 2 File: '/Users/kongbunthong/Library/Developer/CoreSimulator/Devices/..../tmp/image_picker_3912CA1D-AC60-4C84-823F-EB19B630FD1C-11650-0000061E644AD3FA.jpg'
> flutter: It didnt work sorry
The second line shows that there is 2 file overlapping each other, and doesn't that means the 2 files are the same?
And if it is the same, it should print out Should be starting to put the file in. But instead, it prints out: It didn't work sorry.
Any help is VERY MUCH appreciated!
The two files are different File objects and so the equality check will fail.
You can check if the two File paths are the same like this:
if (userProfilePicture.path != image.path)

how to get url from firebase storage to save in firestore

i'am still new in flutter and firebase. I want to ask on how to get the URL file from storage and save it in firestore?
this is the code to upload file.
Future uploadFile() async {
if (file == null) return;
final fileName = basename(file.path);
final destination = 'files/$fileName';
task = FirebaseApi.uploadFile(destination, file);
setState(() {});
if (task == null) return;
final snapshot = await task.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
print('Download-Link: $urlDownload');
}
another related class with the upload file

Flutter Firebase Storage 0.5.0 upload file and video error

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.

Resources