postMultipart method

Future<Response> postMultipart(
  1. String endpoint, {
  2. required dynamic file,
  3. String fieldName = 'file',
  4. Map<String, String>? fields,
  5. Map<String, String>? headers,
})

Make POST request with multipart file upload Accepts File (mobile) or XFile (web)

Implementation

Future<http.Response> postMultipart(
  String endpoint, {
  required dynamic file, // File on mobile, XFile on web
  String fieldName = 'file',
  Map<String, String>? fields,
  Map<String, String>? headers,
}) async {
  try {
    final uri = Uri.parse('${_config.baseUrl}$endpoint');

    if (_config.enableLogging) {
      debugPrint('[ApexKYC] POST Multipart $uri');
      if (kIsWeb) {
        final xFile = file as XFile;
        debugPrint('[ApexKYC] File: XFile (web) - ${xFile.name}');
      } else {
        // Only access File properties on mobile
        debugPrint('[ApexKYC] File: (mobile)');
      }
    }

    final request = http.MultipartRequest('POST', uri);

    // Add headers
    final requestHeaders = _getHeaders(additionalHeaders: headers);
    requestHeaders.remove('Content-Type'); // Let multipart set it
    request.headers.addAll(requestHeaders);

    // Handle file upload differently for web vs mobile
    http.MultipartFile multipartFile;

    if (kIsWeb) {
      // Web platform - use XFile
      final xFile = file as XFile;
      final bytes = await xFile.readAsBytes();
      final filename = xFile.name.isNotEmpty
          ? xFile.name
          : 'image_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final contentType = xFile.mimeType ?? 'image/jpeg';

      multipartFile = http.MultipartFile.fromBytes(
        fieldName,
        bytes,
        filename: filename,
        contentType: MediaType.parse(contentType),
      );
    } else {
      // Mobile platform - use File
      // Use dynamic to avoid type issues with conditional imports
      final fileObj = file;
      final fileStream = _getFileStream(fileObj);
      final fileLength = await _getFileLength(fileObj);
      final filename = _getFileName(fileObj);
      multipartFile = http.MultipartFile(
        fieldName,
        fileStream,
        fileLength,
        filename: filename,
        contentType: MediaType('image', 'jpeg'),
      );
    }

    request.files.add(multipartFile);

    // Add additional fields
    if (fields != null) {
      request.fields.addAll(fields);
    }

    final streamedResponse = await _client
        .send(request)
        .timeout(Duration(seconds: _config.timeoutSeconds));

    final response = await http.Response.fromStream(streamedResponse);

    if (_config.enableLogging) {
      debugPrint(
        '[ApexKYC] Response: ${response.statusCode} ${response.body}',
      );
    }

    return _handleResponse(response);
  } catch (e) {
    if (e is ApexKycException) {
      rethrow;
    }
    throw ApexKycException(
      'Unexpected error: ${e.toString()}',
      originalError: e,
    );
  }
}