我确实有两个函数,它们是selectFile()
和uploadProduct()
。selectFile
包含Image_Picker
和Image_Cropper
。现在我需要从uploadProduct()
中的selectFile
中获取路径和文件,将其上传到我的Firebase存储中,并将URL存储在我的Firebase中,我不知道如何传递它。
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;
}
既然你已经在类中有imagePath
,我想,你可以试试这个:
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
如果imageData
等于app/name/image.jpg
在imageData
上调用split("/")
将得到如下列表:
['app', 'name', 'image.jpg']
你可以看到它是"separate by">
然后,.last
选择列表中的最后一项。