Reputation: 311
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.
Upvotes: 0
Views: 115
Reputation: 1405
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
Upvotes: 1