Flutter http.MultipartRequest 支持布尔值吗?

问题描述 投票:0回答:1

在 Flutter 中,我使用 http.MultipartRequest 作为 POST 图像并将有效负载发送到后端。我的一些有效负载是布尔值,但http.MultipartRequest不支持布尔值。我该如何解决这个问题?

这是我的方法。

  String url,
  Map<String, dynamic> payload,
  File? imageFile,
) async {
  final chatReplyData =
      ChatReplyData(responseStatus: 0, validStatusCode: false);

  try {
    final request = http.MultipartRequest(
      'POST',
      Uri.parse('${getApiPrefix()}$url'),
    );

    // Add image file to the request
    if (imageFile != null) {
      final imageStream = http.ByteStream(imageFile.openRead());
      final imageLength = await imageFile.length();
      final multipartFile = http.MultipartFile(
        'file',
        imageStream,
        imageLength,
        filename: imageFile.path,
      );
      request.files.add(multipartFile);
    }

    // Add other payload data
    payload.forEach((String key, dynamic value) {
      request.fields[key] = value.toString();
    });

    final response = await request.send();

    // get response as json string
    final responseData = await response.stream.bytesToString();
    // Parse response as JSON
    final responseBody = jsonDecode(responseData);

    final responseStatus = response.statusCode;
    chatReplyData.responseStatus = responseStatus;

    debugPrint(
        'myLog: getChatReply -> url = $url, payload = $payload, imageFile = $imageFile');
    debugPrint(
        'myLog: getChatReply -> responseStatus = $responseStatus, responseBody = $responseBody');

    chatReplyData.message = responseBody?['message'];

    return chatReplyData;
  } catch (e) {
    debugPrint('myError: getChatReply -> error = $e');
    return chatReplyData;
  }
}

这里

payload.forEach((String key, dynamic value) {
      request.fields[key] = value.toString();
    });

我不想将所有字段作为String传递。因为我的一些值是boolean

flutter flutter-dependencies hybrid-mobile-app mobile-application
1个回答
0
投票

你试试这个方法,一定会有效果的。

#API定义 未来的 multipartRequest( 网址, 有效负载, 图像文件, ) 异步 { 字符串baseUrl = getBaseUrl();

var request = http.MultipartRequest('POST', Uri.parse('$baseUrl$url'));
request.fields.addAll(payload);

if (imageFile.isNotEmpty) {
  for (var image in imageFile) {
    var file = await http.MultipartFile.fromPath('FileList', image);
    request.files.add(file);
  }
}

try {
  var response = await request.send();
  if (response.statusCode == 200) {
    return {
      "status": response.statusCode,
      "data": await response.stream.bytesToString()
    };
  } else {
    return {"status": response.statusCode, "data": response.reasonPhrase};
  }
} catch (e) {
  showToast('Error uploading file: $e', Colors.red, Colors.white);
}

}

#API 调用

multipartRequest("端点 url", { "payload1":"东西", “有效负载2”:24, “有效负载3”:假,

    },
    files);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.