uploadMediaFile method

Future<void> uploadMediaFile({
  1. required String phoneNumberId,
  2. required String accessToken,
  3. required File file,
  4. required String fileType,
})

Implementation

Future<void> uploadMediaFile({
  required String phoneNumberId,
  required String accessToken,
  required File file,
  required String fileType,
}) async {
  try {
    var uri =
        Uri.parse('https://graph.facebook.com/v20.0/$phoneNumberId/media');

    var request = http.MultipartRequest('POST', uri);
    request.headers.addAll({"Authorization": "Bearer $accessToken"});
    request.fields['messaging_product'] = 'whatsapp';
    request.files.add(await http.MultipartFile.fromPath(
      'file',
      file.path,
      contentType: MediaType.parse(fileType),
    ));

    var resp = await request.send();
    var res = await http.Response.fromStream(resp);

    httpCode = res.statusCode;
    response = res.body;

    if (res.statusCode >= 400) {
      // Handle error status codes
      var jsonResponse = jsonDecode(res.body);
      errorMessage = jsonResponse['error']?['message'] ?? 'Unknown error';
    } else {
      // Handle successful response
      var jsonResponse = jsonDecode(res.body);
      mediaId = jsonResponse['id'] ?? '';
    }
  } catch (e) {
    // Handle exceptions
    error = 'Exception uploading media: $e';
  }
}