I do have two functions and these are selectFile()
and uploadProduct()
. The selectFile
contains the Image_Picker
and Image_Cropper
. and now I need to get the path and file from selectFile
in my uploadProduct()
to upload it on my Firebase Storage and Store the URL in my firestore and I do not know how to pass on it.
PlatformFile? pickedFile;
UploadTask? uploadTask;
String imagePath = "";
Future selectFile() async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image != null) {
final croppedImage = await ImageCropper().cropImage(
sourcePath: image!.path,
aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
compressQuality: 100,
maxWidth: 450,
maxHeight: 450,
compressFormat: ImageCompressFormat.jpg,
aspectRatioPresets: [CropAspectRatioPreset.square],
);
setState(() {
imagePath = croppedImage!.path;
});
}
} on PlatformException catch (e) {
print(e);
Navigator.of(context).pop();
}
}
Future uploadProduct() async {
// i should be passing here the path
final path = 'products/${pickedFile!.name}';
// I should be passing here the file
final file = File(croppedImage!.path);
final ref = FirebaseStorage.instance.ref().child(path);
uploadTask = ref.putFile(file);
final snapshot = await uploadTask!.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
var url = urlDownload.toString();
// I haven't started the storing of the url to firestore since i can't upload the file on firestore storage.
print(url);
return url;
}
CodePudding user response:
Since you already have imagePath
in the class, I suppose, you can try this:
Future uploadProduct() async {
final path = 'products/${imagePath.split("/").last}';
final file = File(imagePath);
final ref = FirebaseStorage.instance.ref().child(path);
uploadTask = ref.putFile(file);
final snapshot = await uploadTask!.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
var url = urlDownload.toString();
print(url);
return url;
}
split and .last explanation
So if imageData
is something like app/name/image.jpg
Calling split("/")
on imageData
would give a list like:
['app', 'name', 'image.jpg']
You can see it as "separate by"
Then, .last
picks the last item in the list.