从 Flask 服务器向 Flutter 发送 JSON 数据时,数据不完整,每次在 80-90 个字符后就会被截断。我该如何解决这个问题?
当我拍照并将其发送到 Flask 服务器时,服务器返回 JSON 格式的值,但数据在中间被切断。我该如何解决这个问题?
static Future<AiData> uploadImage(String imagePath) async {
var formData = FormData.fromMap({
'file': await MultipartFile.fromFile(imagePath),
});
try {
final response = await flaskDio.post(
'/upload',
data: formData,
options: Options(
validateStatus: (status) {
return status! < 500;
},
),
);
if (response.statusCode == 200) {
// JSON 형식의 응답 데이터를 문자열로 로깅
final responseDataString = response.data.toString();
logger.i('Raw response data: $responseDataString');
try {
// 응답 데이터를 JSON으로 디코딩
var responseData = jsonDecode(responseDataString) as Map<String, dynamic>;
logger.i('Decoded response data: $responseData');
return AiData.fromJson(responseData);
} catch (e) {
logger.e('Failed to decode JSON: $e');
throw Exception('Failed to decode JSON: $e');
}
} else {
logger.e('Image upload failed.');
throw Exception('Failed to upload image: ${response.statusMessage}');
}
} catch (e) {
logger.e('Image upload failed: $e');
if (e is DioError) {
logger.e('Dio error message: ${e.message}');
logger.e('Dio error response: ${e.response}');
logger.e('Dio error response data: ${e.response?.data}');
}
throw Exception('Image upload failed: $e');
}
}
我有一种感觉,这可能是日志记录的截断问题,而不是实际输出的问题。
这里有一个线程,其中建议的解决方案是实现此自定义打印机,将输出分块为适当的大小:
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
执行此操作以确认您的 json 没有问题:
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
if (response.statusCode == 200) {
// JSON 형식의 응답 데이터를 문자열로 로깅
final responseDataString = response.data.toString();
printWrapped('Raw response data: $responseDataString');
}