You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中jsonEncode请求返回500状态码问题求助

问题分析与解决:Flutter请求HF Space接口返回500错误

你的问题核心在于硬编码的图片base64字符串包含完整的Data URI前缀,而用户上传图片转换后的base64只有纯编码内容,缺少前缀导致后端无法正确解析图片数据,返回500错误。

关键格式差异:

  • 硬编码的有效格式:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==
  • 用户生成的格式:仅包含纯base64编码(缺少data:image/png;base64,前缀)

修改后的代码:

在生成base64String时添加完整的Data URI前缀即可:

onPressed: () async {
  Uint8List imageBytes = await imageFile!.readAsBytes();
  img.Image image = img.decodeImage(imageBytes)!;
  img.Image pngImage = img.copyResize(image, width: 800);
  Uint8List pngBytes = img.encodePng(pngImage);
  // 补充Data URI前缀
  String base64String = 'data:image/png;base64,' + base64Encode(pngBytes);
  String textInput = fieldText.text;
  
  if (imageFile != null &&
      base64String.isNotEmpty &&
      textInput.isNotEmpty) {
    final url = Uri.parse('https://anash-visual-qa.hf.space/run/predict');
    final response = await http.post(
      url,
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'data': [base64String, textInput],
      }),
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body)['data'];
      print(data);
      print('Request Success with status: ${response.statusCode}.');
    } else {
      print('Request failed with status: ${response.statusCode}.');
      // 可打印response.body查看后端具体错误信息
      print('Error details: ${response.body}');
    }

    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => output(
                response.body,
              )),
    );
  } else {
    print('Error: Image file, base64 string, or text input is missing.');
  }
}

额外验证建议:

  • 打印生成的base64String,确认格式与硬编码示例完全一致
  • 若仍报错,查看response.body的具体错误信息,排查是否存在图片尺寸、编码格式等其他问题

内容的提问来源于stack exchange,提问作者dhyanmohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 23:42:17