uploadFile method

Future<ApiResponse> uploadFile(
  1. String endpoint,
  2. String fieldName,
  3. File file, {
  4. Map<String, String>? fields,
  5. String? fileNameField,
})

Make a POST request with file upload

Implementation

Future<ApiResponse> uploadFile(
  String endpoint,
  String fieldName,
  File file, {
  Map<String, String>? fields,
  String? fileNameField,
}) async {
  try {
    final uri = Uri.parse('${ScanProConfig.apiUrl}$endpoint');

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

    // Add API key header
    request.headers.addAll({'x-api-key': ScanProConfig.apiKey});

    // Get file details
    final fileName = file.path.split('/').last;
    final fileBytes = await file.readAsBytes();
    final fileSize = fileBytes.length;

    // Check file size
    if (fileSize > ScanProConfig.maxFileSize) {
      return ApiResponse(
        success: false,
        error:
            'File size exceeds maximum allowed size of ${ScanProConfig.maxFileSize ~/ (1024 * 1024)}MB',
      );
    }

    // Determine content type based on file extension
    final fileExtension = fileName.split('.').last.toLowerCase();
    String contentType;

    switch (fileExtension) {
      case 'pdf':
        contentType = 'application/pdf';
        break;
      case 'jpg':
      case 'jpeg':
        contentType = 'image/jpeg';
        break;
      case 'png':
        contentType = 'image/png';
        break;
      case 'docx':
        contentType =
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        break;
      case 'xlsx':
        contentType =
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        break;
      case 'pptx':
        contentType =
            'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      default:
        contentType = 'application/octet-stream';
    }

    // Add the file
    request.files.add(
      http.MultipartFile.fromBytes(
        fieldName,
        fileBytes,
        filename: fileName,
        contentType: MediaType.parse(contentType),
      ),
    );

    // Add filename field if provided
    if (fileNameField != null) {
      request.fields[fileNameField] = fileName;
    }

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

    // Send the request
    final streamedResponse = await request.send().timeout(
          ScanProConfig.timeout,
        );
    final response = await http.Response.fromStream(streamedResponse);

    return _handleResponse(response);
  } catch (e) {
    return ApiResponse(success: false, error: e.toString());
  }
}