multipartRequest method

Future multipartRequest({
  1. required Method method,
  2. required String url,
  3. Map<String, dynamic>? body,
  4. Map<String, dynamic>? queryParams,
  5. Map<String, String>? headers,
  6. OnUploadProgressCallback? progress,
})

Implementation

Future<dynamic> multipartRequest({
  required Method method,
  required String url,
  Map<String, dynamic>? body,
  Map<String, dynamic>? queryParams,
  Map<String, String>? headers,
  OnUploadProgressCallback? progress,
}) async {
  // await ConnectionManager.readyToExecuteAPIRequest(force: bypassAuth);

  final request = MultipartRequest(
    method.asString().toUpperCase(),
    Uri(
      scheme: isLocal ? 'http' : 'https',
      host: baseUrl,
      path: url,
      queryParameters: _convertQueryParams(queryParams ?? {}),
    ),
    onProgress: progress,
  );
  this.request = request;

  body?.forEach((key, value) {
    if (value is FileInfo) {
      if (value.fileBytes != null) {
        //* Bytes
        final part = http.MultipartFile.fromBytes(
          key,
          value.fileBytes!,
          filename: value.name,
          contentType: value.mimeType == null || value.mimeType == ""
              ? null
              : MediaType.parse(value.mimeType!),
        );
        request.files.add(part);
      } else {
        //* File
        final part = http.MultipartFile(
          key,
          value.file!.openRead(),
          value.file!.lengthSync(),
          filename: value.name,
          contentType: MediaType.parse(value.mimeType!),
        );
        request.files.add(part);
      }
    } else if (value is List<String>) {
      request.fields[key] = value.join(',');
    } else if (value is List) {
      final converted = value.map((e) => jsonEncode(e));
      request.fields[key] = converted.join(',');
    } else if (value is String) {
      request.fields[key] = value;
    } else if (value != null) {
      request.fields[key] = jsonEncode(value);
    }
  });

  request.headers.addAll(commonHeaders());
  if (headers != null && headers.isNotEmpty) request.headers.addAll(headers);

  String? reqId = body?['request_id'];
  if (reqId != null) uploadRequests[reqId] = request;

  final res = await request.send();
  final result = await http.Response.fromStream(res);

  uploadRequests.remove(reqId);
  return _response(result);
}