uploadImage method

Future<CloudinaryResponse> uploadImage(
  1. String imagePath, {
  2. String? imageFilename,
  3. String? folder,
})

Implementation

Future<CloudinaryResponse> uploadImage(
  String imagePath, {
  String? imageFilename,
  String? folder,
}) async {
  var timeStamp = DateTime.now().millisecondsSinceEpoch;

  var params = <String, dynamic>{};
  if (_apiKey == null) {
    throw Exception('apiKey and apiSecret must not be null');
  }

  params['api_key'] = _apiKey;

  // ignore: unnecessary_null_comparison
  if (imagePath == null) {
    throw Exception('imagePath must not be null');
  }
  var publicId = imagePath.split('/').last;
  publicId = publicId.split('.')[0];

  if (imageFilename != null) {
    publicId = imageFilename.split('.')[0];
  } else {
    imageFilename = publicId;
  }

  params['folder'] = folder;

  params['public_id'] = publicId;

  params['file'] = await MultipartFile.fromFile(imagePath, filename: imageFilename);
  params['timestamp'] = timeStamp;

  params['signature'] = getSignature(folder, publicId, timeStamp);

  var formData = FormData.fromMap(params);

  var dio = await getApiClient();
  var response = await dio.post('$_cloudName/image/upload', data: formData);
  try {
    return CloudinaryResponse.fromJsonMap(response.data);
  } on Exception catch (error, stacktrace) {
    debugPrint('Exception occured: $error stackTrace: $stacktrace');
    return CloudinaryResponse.fromError('$error');
  }
}