uploadFile method

Future<void> uploadFile(
  1. String localFilePath,
  2. String remotePath, {
  3. dynamic onProgress(
    1. int sent,
    2. int total
    )?,
})

Implementation

Future<void> uploadFile(
  String localFilePath,
  String remotePath, {
  Function(int sent, int total)? onProgress,
}) async {
  try {
    final file = File(localFilePath);
    if (!await file.exists()) {
      throw Exception('File does not exist: $localFilePath');
    }

    final fileLength = await file.length();
    final url = Uri.parse('$baseUrl$remotePath');

    // Create a multipart request with progress tracking
    final request = http.StreamedRequest('PUT', url);
    request.headers.addAll(_getHeaders());
    request.contentLength = fileLength;

    // Track upload progress
    int bytesSent = 0;
    final fileStream = file.openRead();

    fileStream.listen(
      (chunk) {
        request.sink.add(chunk);
        bytesSent += chunk.length;
        if (onProgress != null) {
          onProgress(bytesSent, fileLength);
        }
      },
      onDone: () {
        request.sink.close();
      },
      onError: (error) {
        request.sink.addError(error);
      },
      cancelOnError: true,
    );

    // Send request with extended timeout for large files
    final response = await request.send().timeout(
      const Duration(minutes: 30),
      onTimeout: () {
        throw Exception('Upload timeout - please check your connection');
      },
    );

    if (response.statusCode == 201 || response.statusCode == 204) {
      // Upload successful
    } else {
      await response.stream.bytesToString(); // Consume response
      throw Exception('Failed to upload file: ${response.statusCode}');
    }
  } catch (e) {
    rethrow;
  }
}