Philip Kalela
Philip Kalela

Reputation: 375

How can I send .wav file to an api that only accepts 'content-type':'audio/wav' with flutter http

I have the code below to send a recorded wav file to the wit.ai API.

      Map<String, String> headers = {
        'Content-Type': 'audio/wav',
        'Authorization': "Bearer $witPublicAPIKey"
      };
      http.MultipartRequest request =
          http.MultipartRequest('POST', Uri.parse(BASE_URL + url));
      request.headers.clear();
      request.headers.addAll(headers);
      request.headers.update('content-type', (value) => 'audio/wav');
      request.headers.update('Content-Type', (value) => 'audio/wav');
      request.headers.update('Content-Type', (value) => 'audio/wav');
      request.files.add(await http.MultipartFile.fromPath('audio', audioUri,
          filename: '${audioUri.split('/').last}.wav',
          contentType: MediaType('audio', 'wav')));
      print("request header is ${request.headers}");
      print("request is ${request}");
      http.Response res = await http.Response.fromStream(await request.send());
      print("Response: ${res.body}");

      responseJson = _response(res); 

I get this error "error": "Unsupported content-type: 'multipart/form-data;boundary=dart-http-boundary-bpY_n6t9LVcEAVFf7qGYHXDU.H_s1alCjaGGk++6ZOcJ5M4iRFT'" as the response. It seems from the docs that HTTP overrides my content-type: audio/wav header and replaces it with multipart/form-data. I would like to upload the wav through my flutter app. Any idea how I can achieve that? Thanks.

Upvotes: 0

Views: 3618

Answers (1)

Raju Ugale
Raju Ugale

Reputation: 4281

This should work:

String url = "https://api.com";

    var request = new http.MultipartRequest("POST", Uri.parse(url));
    request.headers['Authorization'] =
    'Bearer xxxxxxxxxxxxxxxxx';
    request.headers['x-app-key'] = '943691';
    request.fields['category'] =
    '<letter>h</letter><letter>o</letter><letter>m</letter><letter>e</letter>';
    request.fields['categoryA'] = '<letter>a</letter>';
    
    request.files.add(await http.MultipartFile.fromPath(
      'file',
      '/data/user/0/com/cache/abc.wav',
      contentType: MediaType('application', 'audio/wav'),
    ));

    try {
    var response = await request.send();
    var res = await http.Response.fromStream(response);

    if (res.statusCode == 200)
      print("SUCCESS! 200 HTTP");

      print("HTTP CODE:${res.statusCode}");
      String respString = res.body;
      print("respString::$respString");
    SpellRoot spellRoot=spellRootFromJson(respString);
    return spellRoot;
    } catch (e, s) {
      print("ERRR 200 responsecode");
      print("$e __ $s");
    
  }

Upvotes: 0

Related Questions