startUpload method
Future<String>
startUpload({
- required String filePath,
- required String uploadUrl,
- Map<
String, String> ? headers, - Map<
String, String> ? fields,
override
Starts a file upload operation in the background.
The upload continues even if the app moves to the background. Progress can be tracked using getUploadProgress.
Parameters:
filePath: Local path of the file to uploaduploadUrl: The URL where the file should be uploaded toheaders: Optional HTTP headers to include in the requestfields: Optional form fields to include in the multipart request
Returns a task ID string that can be used to track progress or cancel the task.
Throws an Exception if the upload fails to start.
Implementation
@override
Future<String> startUpload({
required String filePath,
required String uploadUrl,
Map<String, String>? headers,
Map<String, String>? fields,
}) async {
final taskId = DateTime.now().toIso8601String();
_taskDetails[taskId] = {
'type': 'upload',
'url': uploadUrl,
'path': filePath,
'createdAt': DateTime.now().toIso8601String(),
};
_progressControllers[taskId] = StreamController<double>();
// Verify file exists
if (!await File(filePath).exists()) {
throw Exception('File not found: $filePath');
}
await _enqueueOperation(() {
// Simulate upload progress
Timer.periodic(const Duration(milliseconds: 100), (timer) {
final controller = _progressControllers[taskId];
if (controller == null || controller.isClosed) {
timer.cancel();
_operationComplete();
return;
}
double progress = 0.0;
controller.addStream(Stream.periodic(
const Duration(milliseconds: 100),
(count) {
progress = (count + 1) / 10;
if (progress >= 1.0) {
timer.cancel();
_completedTasks[taskId] = true;
_operationComplete();
}
return progress;
},
).take(10));
});
});
return taskId;
}