multiPartFileUpload<E> method

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

Implementation

Future<Either<ApiFailure, E>> multiPartFileUpload<E>(
  String filePath,
  String tag,
  String url,
  Map<String, dynamic> body,
  E Function(dynamic) fromJsonE,
) async {
  try {
    bool isFileUpload = false;
    var headers = {
      'content-type': 'multipart/form-data',
      'Authorization':
          'Bearer ',
    };
    debugPrint('<>url $url');
    var request = http.MultipartRequest('POST', Uri.parse(url))
      ..headers.addAll(headers);

    if (filePath != '') {
      isFileUpload = true;

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

    body.forEach((key, value) {
      if (!isFileUpload) {
        if (key == 'profile_image') {
          request.fields[key] = "";
        } else {
          request.fields[key] = value;
        }
      } else {
        if (key != 'profile_image') {
          request.fields[key] = value;
        }
      }

      //remove profile_image from form-data
    });

    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: ${jsonEncode(decodedJson).toString()}');
    if (response.statusCode == 200 || response.statusCode == 204) {
      final responseObj = fromJsonE(decodedJson);
      return Right(responseObj);
    } else {
      return Left(
        ApiFailure.serverError(
          message: getValidationMessage(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.'),
    );
  }
}