fileUpload method

Future<BaseDataAPI> fileUpload(
  1. dynamic url, {
  2. dynamic body,
  3. Map<String, dynamic>? headers,
  4. ApiMethod method = ApiMethod.POST,
  5. required File file,
})

Implementation

Future<BaseDataAPI> fileUpload(url,
    {dynamic body,
    Map<String, dynamic>? headers,
    ApiMethod method = ApiMethod.POST,
    required File file}) async {
  /// Check internet connection is available
  /// * If internet connection is not available,
  ///  return [ApiStatus.INTERNET_UNAVAILABLE]
  /// * If internet connection is available,
  /// continue to fetch data

  if (!(await BaseUtils.checkConnection())) {
    return BaseDataAPI(
      apiStatus: ApiStatus.INTERNET_UNAVAILABLE,
    );
  }

  /// Continue to fetch data
  /// response is response of API
  Response response;
  printLogYellow('API:${apiMethod[method]}|================--------------->');
  print('url: $domain$url');
  print('header: $headers');
  print('body: $body');
  try {
    Options options = Options();
    options.method = apiMethod[method];
    options.headers = headers;
    String fileName = file.path.split('/').last;
    FormData formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(file.path, filename: fileName),
    });
    response =
        await _dio.request(domain + url, data: formData, options: options);
  } on DioError catch (e) {
    /// If error is DioError, return [ApiStatus.FAILED]
    printLogError('Error [${apiMethod[method]} API]: $e');
    printLogYellow(
        'END API ${apiMethod[method]}<---------------================|');
    return BaseDataAPI(apiStatus: ApiStatus.FAILED);
  }
  // If response.data is DioError, return [ApiStatus.FAILED]
  if (response.data is DioError) {
    printLogError('Error [${apiMethod[method]} API]: ${response.data}');
    printLogYellow('END API GET<---------------================|');
    return BaseDataAPI(apiStatus: ApiStatus.FAILED);
  }
  // If response.data is not null, return [response.data ,ApiStatus.SUCCEEDED]
  printLogSusscess('Success [${apiMethod[method]} API]: ${response.data}');
  printLogYellow(
      'END API ${apiMethod[method]}<---------------================|');
  return BaseDataAPI(object: response.data, apiStatus: ApiStatus.SUCCEEDED);
}