76 lines
2.1 KiB
Dart
76 lines
2.1 KiB
Dart
import 'package:file_picker/file_picker.dart';
|
|
|
|
class FileUploadService {
|
|
FileUploadService._();
|
|
static final FileUploadService _instance = FileUploadService._();
|
|
factory FileUploadService() => _instance;
|
|
|
|
PlatformFile? singleFile;
|
|
List<PlatformFile> multipleFiles = [];
|
|
|
|
/// Default allowed extensions
|
|
static const defaultAllowedExtensions = ['pdf', 'png', 'jpg', 'jpeg'];
|
|
// static const allowedExtensions = ['pdf', 'png', 'jpg', 'jpeg'];
|
|
|
|
Future<String?> pickSingleFile({
|
|
int maxFileSizeInMB = 5,
|
|
List<String>? allowedExtensions,
|
|
}) async {
|
|
final extensions = allowedExtensions ?? defaultAllowedExtensions;
|
|
final result = await FilePicker.platform.pickFiles(
|
|
allowMultiple: false,
|
|
withData: true,
|
|
type: FileType.custom,
|
|
allowedExtensions: extensions,
|
|
);
|
|
|
|
if (result != null && result.files.isNotEmpty) {
|
|
final file = result.files.first;
|
|
final ext = file.extension?.toLowerCase() ?? '';
|
|
// final sizeInMB = file.size / (1024 * 1024);
|
|
|
|
if (!extensions.contains(ext)) {
|
|
return "Unsupported format: ${file.name}";
|
|
}
|
|
// if (sizeInMB > maxFileSizeInMB) {
|
|
// return "File too large (${file.name}). Max $maxFileSizeInMB MB allowed.";
|
|
// }
|
|
|
|
singleFile = file;
|
|
}
|
|
return null; // success
|
|
}
|
|
|
|
Future<String?> pickMultipleFiles({
|
|
int maxFileSizeInMB = 5,
|
|
List<String>? allowedExtensions,
|
|
}) async {
|
|
final extensions = allowedExtensions ?? defaultAllowedExtensions;
|
|
final result = await FilePicker.platform.pickFiles(
|
|
allowMultiple: true,
|
|
withData: true,
|
|
type: FileType.custom,
|
|
allowedExtensions: extensions,
|
|
);
|
|
|
|
if (result != null && result.files.isNotEmpty) {
|
|
for (final file in result.files) {
|
|
final ext = file.extension?.toLowerCase() ?? '';
|
|
if (!extensions.contains(ext)) {
|
|
return "Unsupported format: ${file.name}";
|
|
}
|
|
}
|
|
multipleFiles = result.files;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
void clearSingle() {
|
|
singleFile = null;
|
|
}
|
|
|
|
void clearMultiple() {
|
|
multipleFiles = [];
|
|
}
|
|
}
|