【问题标题】:Flutter : API isn't respond when send Field?Flutter:发送字段时API没有响应?
【发布时间】:2021-03-30 13:28:19
【问题描述】:

我为带有上传图片的 Multipart API 发布请求创建了一个 Future 函数。但是当我使用 request.fields.addAll(updateProfileInfo.toJson()); 它没有响应。

这里是代码示例 -

    Future<Map<String, dynamic>> updateprofile(
      UpdateProfileInfo updateProfileInfo, File imageFile) async {
    var stream = http.ByteStream(Stream.castFrom(imageFile.openRead()));
    var length = await imageFile.length();

    String url = "$baseAPIUrl/update-profile-info";
    String _token = await SavedData().loadToken();
    String authorization = "Bearer $_token";

    final body = jsonEncode(updateProfileInfo);
    final headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      "Authorization": authorization
    };

    var request = http.MultipartRequest("POST", Uri.parse(url));
    var multipartFile = http.MultipartFile('image', stream, length,
        filename: basename(imageFile.path));
    request.headers.addAll(headers);
    request.files.add(multipartFile);

    request.fields.addAll(updateProfileInfo.toJson());

    http.StreamedResponse response = await request.send();

    String respStr = await response.stream.bytesToString();
    dynamic respJson;

    try {
      respJson = jsonDecode(respStr);
    } on FormatException catch (e) {
      print(e.toString());
    }

    print('API ${response.statusCode}\n  $respJson');

    bool isSuccess = response.statusCode == 200;
    var data = json.decode(respStr);

    return {
      'isSuccess': isSuccess,
      "message": isSuccess ? data["success"]["message"] : null,
      "name": isSuccess ? data["success"]["name"] : null,
      "classgroup": isSuccess ? data["success"]["classgroup"] : null,
      "image": isSuccess ? data["success"]["image"] : null,
      "error": isSuccess ? null : data['error']['message'],
    };
  }

如何发送正文字段请求?请有人帮助我

【问题讨论】:

    标签: api flutter response multipart


    【解决方案1】:

    request.fields 是&lt;String, String&gt; 类型的映射。所以你所有的字段数据都必须是字符串。否则updateProfileInfo.toJson() 必须返回Map&lt;String, String&gt; 类型的对象。

    希望这可以解决您的问题。

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 2022-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多