我如何发送.wav文件到一个只接受'content-type'的API:'audio/wav'与flutter http

e0bqpujr  于 2023-05-23  发布在  Flutter
关注(0)|答案(1)|浏览(214)

我有下面的代码来发送一个录制的wav文件到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);

我得到这个错误"error": "Unsupported content-type: 'multipart/form-data;boundary=dart-http-boundary-bpY_n6t9LVcEAVFf7qGYHXDU.H_s1alCjaGGk++6ZOcJ5M4iRFT'"作为响应。从docs看,HTTP覆盖了我的content-type: audio/wav头并将其替换为multipart/form-data。我想通过我的Flutter应用程序上传wav。你知道我该怎么做吗谢谢。

ehxuflar

ehxuflar1#

这应该可以工作:

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");
    
  }

相关问题