startUpload method

  1. @override
Future<String> startUpload({
  1. required String filePath,
  2. required String uploadUrl,
  3. Map<String, String>? headers,
  4. 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 upload
  • uploadUrl: The URL where the file should be uploaded to
  • headers: Optional HTTP headers to include in the request
  • fields: 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;
}