handleUpload method
- BuildContext context
Handles file upload by reading its contents and encrypting it for upload.
Implementation
Future<void> handleUpload(BuildContext context) async {
if (state.uploadFile == null) return;
try {
state = state.copyWith(uploadInProgress: true, uploadDone: false);
final file = File(state.uploadFile!);
String fileContent;
// For text files, we directly read the content.
// For binary files, we encode them into base64 format.
if (isTextFile(state.uploadFile!)) {
fileContent = await file.readAsString();
} else {
final bytes = await file.readAsBytes();
fileContent = base64Encode(bytes);
}
// Sanitise file name and append encryption extension.
String sanitizedFileName = path
.basename(state.uploadFile!)
.replaceAll(RegExp(r'[^a-zA-Z0-9._-]'), '_')
.replaceAll(RegExp(r'\.enc\.ttl$'), '');
final remoteFileName = '$sanitizedFileName.enc.ttl';
final cleanFileName = sanitizedFileName;
// Extract the subdirectory path.
String? subPath = state.currentPath?.replaceFirst(basePath, '').trim();
String uploadPath = subPath == null || subPath.isEmpty
? remoteFileName
: '${subPath.startsWith("/") ? subPath.substring(1) : subPath}/$remoteFileName';
// debugPrint('Upload path: $uploadPath');
if (!context.mounted) return;
// Upload file with encryption.
final result = await writePod(
uploadPath,
fileContent,
context,
const Text('Upload'),
encrypted: true,
);
state = state.copyWith(
uploadDone: result == SolidFunctionCallStatus.success,
uploadInProgress: false,
remoteFileName: remoteFileName,
cleanFileName: cleanFileName,
);
if (result == SolidFunctionCallStatus.success) {
// Show success message.
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('File uploaded successfully'),
backgroundColor: Theme.of(context).colorScheme.tertiary,
),
);
// Call the refresh callback to update the browser.
_refreshCallback?.call();
}
} else if (context.mounted) {
showAlert(
context,
'Upload failed - please check your connection and permissions.',
);
}
} catch (e) {
if (context.mounted) {
showAlert(context, 'Upload error: ${e.toString()}');
debugPrint('Upload error: $e');
}
state = state.copyWith(uploadInProgress: false);
}
}