uploadMediaByPath method

Future<DialoguewiseResponse> uploadMediaByPath(
  1. String filePath
)

Uploads an image or file given file path and returns the URL of uploaded file. Takes filePath which is the path to the local file. Throws ArgumentError if the file path is empty. Throws FileSystemException if the file does not exist.

This is only supported on mobile platforms.

Implementation

Future<DialoguewiseResponse> uploadMediaByPath(String filePath) async {
  if (filePath.isEmpty) {
    throw ArgumentError(
        "Please provide the local path of file to be uploaded.");
  } else if (FileSystemEntity.typeSync(filePath) ==
      FileSystemEntityType.notFound) {
    throw FileSystemException("Unable to find file $filePath.");
  }

  final apiUrl = '$apiBaseUrl${Endpoints.uploadMedia}';
  final uri = Uri.parse(apiUrl);
  final httpRequest = http.MultipartRequest('POST', uri)
    ..headers['Access-Control-Allow-origin'] = '*'
    ..headers['Access-Control-Allow-Methods'] = '*'
    ..headers['Access-Control-Allow-Headers'] = 'Content-Type, Access-Token'
    ..headers['Access-Token'] = accessToken
    ..files.add(await http.MultipartFile.fromPath('file', filePath));
  final response = await httpRequest.send();

  var dialogueWiseResponse = DialoguewiseResponse(
    statusCode: response.statusCode,
    reasonPhrase: response.reasonPhrase ?? 'Something went wrong',
  );

  final responseBody = await response.stream.bytesToString();

  if (responseBody.isNotEmpty) {
    dialogueWiseResponse.response =
        jsonDecode(responseBody) as Map<String, dynamic>;
  }

  return dialogueWiseResponse;
}