multiPartFileUploadToClient<E> method

Future<Either<ApiFailure, E>> multiPartFileUploadToClient<E>(
  1. String filePath,
  2. String tag,
  3. String url,
  4. Map<String, dynamic> body,
  5. String jwtToken,
  6. E fromJsonE(
    1. dynamic
    ),
)

Implementation

Future<Either<ApiFailure, E>> multiPartFileUploadToClient<E>(
  String filePath,
  String tag,
  String url,
  Map<String, dynamic> body,
  String jwtToken,
  E Function(dynamic) fromJsonE,
) async {
  try {
    var headers = {'Authorization': 'Bearer $jwtToken'};

    var request = http.MultipartRequest('POST', Uri.parse(url))
      ..headers.addAll(headers);

    if (filePath != '') {
      request.files.add(
        await http.MultipartFile.fromPath(
          tag,
          filePath,
          filename: filePath.split('/').last,
        ),
      );
    }

    debugPrint('<>Request Body :$body');

    body.forEach((key, value) {
      request.fields[key] = value;
    });

    var streamedResponse = await request.send();
    var response = await http.Response.fromStream(streamedResponse);

    debugPrint('Response url: ${url}');
    debugPrint('Response Status Code: ${response.statusCode}');
    var decodedJson = response.body.isNotEmpty
        ? jsonDecode(response.body)
        : null;

    debugPrint('Response Body: ${decodedJson?.toString()}');
    if (response.statusCode == 200 || response.statusCode == 204) {
      final responseObj = fromJsonE(decodedJson);
      return Right(responseObj);
    } else {
      return Left(
        ApiFailure.serverError(
          message: consolidateErrorMessages(decodedJson),
        ),
      );
    }
  } catch (e) {
    debugPrint('Error: $e');
    if (e is SocketException) {
      return const Left(
        ApiFailure.clientError(message: 'Failed to connect to server.'),
      );
    }
    return const Left(
      ApiFailure.clientError(message: 'An unknown error occurred.'),
    );
  }
}