diff --git a/lib/src/modules/common/file_upload/file_uploader.dart b/lib/src/modules/common/file_upload/file_uploader.dart index 2d355aa..75ee500 100644 --- a/lib/src/modules/common/file_upload/file_uploader.dart +++ b/lib/src/modules/common/file_upload/file_uploader.dart @@ -1,44 +1,70 @@ -import 'package:fa_flutter_core/fa_flutter_core.dart'; +import 'package:image_picker/image_picker.dart'; import 'package:file_picker/file_picker.dart'; -import 'package:open_file/src/platform/open_file.dart'; +import 'package:open_file/open_file.dart'; class FileService { FileService._(); - /// Return the Clicked Image + /// Picks an image and returns a `PlatformFile`. + /// The file size should be in MB. + /// No limit for file size if [requiredFileSize] is null + /// this will throw error if file size exceeds [requiredFileSize]. + static Future pickImage( - ImageSource source, String? name) async { + ImageSource source, String? name, double? requiredFileSize) async { final pickedFile = await ImagePicker().pickImage(source: source); if (pickedFile != null) { + if (requiredFileSize != null) { + final fileSizeInBytes = requiredFileSize * 1024 * 1024; + final pickedFileSize = await pickedFile.length(); + + if (pickedFileSize > fileSizeInBytes) { + throw Exception("File size exceeds the $requiredFileSize MB limit"); + } + } + return PlatformFile( name: name ?? pickedFile.name, size: await pickedFile.length(), path: pickedFile.path, ); } + return null; } - /// Return the Picked File from the System - /// handled extensions are [pdf, jpeg, jpg, png] - /// We can add more via [extension] parameter - static Future pickDocument(List? extensions) async { + /// Picks a document from the system and returns a `PlatformFile`. + /// Handled extensions are [pdf, jpeg, jpg, png]. More can be added via the `extensions` parameter. + /// The file size should be in MB. + /// No limit for file size if [requiredFileSize] is null + /// this will throw error if file size exceeds [requiredFileSize]. + + static Future pickDocument( + List? extensions, double? requiredFileSize) async { FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, - allowedExtensions: extensions ?? - [ - 'pdf', - 'jpg', - 'jpeg', - 'png', - ], + allowedExtensions: extensions ?? ['pdf', 'jpg', 'jpeg', 'png'], ); - if (result != null) return result.files.first; + + if (result != null && result.files.isNotEmpty) { + final pickedFile = result.files.first; + + if (requiredFileSize != null) { + final fileSizeInBytes = requiredFileSize * 1024 * 1024; + + if (pickedFile.size > fileSizeInBytes) { + throw Exception("File size exceeds the $requiredFileSize MB limit"); + } + } + + return pickedFile; + } + return null; } - /// Open the DOC + /// Opens the document at the specified path. static void openFile(String path) { OpenFile.open(path); }