You need to enable JavaScript to run this app. Flutter中如何将图片以base64字符串形式提交至JSON API服务器
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何将图片以base64字符串形式提交至JSON API服务器

Flutter 实现 base64 图片提交 JSON API 完整方案

1. 优化本地图片数据模型

原有ImageUploadModel仅存储本地File对象,重复读取字节转base64会造成不必要的IO开销,改造后直接在模型中持久化存储已转换的base64字符串,减少重复计算。

// 替换原有ImageUploadModel实现
class ImageUploadModel {
  File imageFile;
  String base64Str; // 新增字段存储转换完成的base64字符串

  ImageUploadModel({
    this.imageFile,
    this.base64Str,
  });
}

2. 选图完成后同步生成base64数据

替换原有getFileImage逻辑,选图拿到本地文件后直接异步读取字节、转换base64存入模型,避免在界面渲染时临时同步读文件造成UI卡顿。

void getFileImage(int index) async {
  _imageFile.then((file) async {
    if(file == null) return; // 兼容用户取消选图的边界场景
    // 异步读取文件字节转base64,不阻塞UI线程
    List<int> imageBytes = await file.readAsBytes();
    String base64Image = base64Encode(imageBytes);
    setState(() {
      ImageUploadModel imageUpload = ImageUploadModel(
        imageFile: file,
        base64Str: base64Image
      );
      images.replaceRange(index, index + 1, [imageUpload]);
    });
  });
}

注意:原有代码在GridView的build方法中使用readAsBytesSync同步读文件,会在界面重绘时反复触发文件IO,容易造成列表滑动卡顿,替换成上述异步读取逻辑后会大幅优化性能。

3. 调整接口服务层逻辑

改造原有postImage方法,将base64字符串作为入参传入,替换请求中Attachment的空占位,同时补充JSON格式请求头,避免服务器解析异常。

Future<ImageModel> postImage(String attachmentBase64) async {
  // 组装请求参数
  Map<String, dynamic> requestData = {
    "Attachment": attachmentBase64
  };
  String body = json.encode(requestData);

  final http.Response response = await http.post(
    // 替换为实际业务接口地址
    'https://你的接口域名/上传接口路径',
    headers: {
      'Content-Type': 'application/json' // 明确声明请求格式为JSON
    },
    body: body,
  );

  print('接口返回内容:${response.body}');
  print('发送的请求体:$body');

  if (response.statusCode == 200) {
    return ImageModel.fromJson(
      jsonDecode(response.body),
    );
  } else {
    throw Exception('图片提交失败,服务端返回状态码:${response.statusCode}');
  }
}

4. 实现发送按钮的完整交互逻辑

在页面状态类中新增上传状态标识,防止请求过程中用户重复点击,替换原有空的send按钮实现:

  • 先在_PickImagesState类中新增状态变量
bool _isUploading = false;
  • 替换原有send按钮的代码
RaisedButton(
  child: _isUploading 
    ? const CircularProgressIndicator(color: Colors.white) 
    : const Text('send'),
  onPressed: _isUploading ? null : () async {
    // 过滤出所有已选择的有效图片
    List<ImageUploadModel> selectedImages = images
      .whereType<ImageUploadModel>()
      .toList();
    
    if(selectedImages.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先选择要上传的图片'))
      );
      return;
    }

    setState(() {
      _isUploading = true;
    });

    try {
      // 按现有接口单附件要求,取首张已选图片的base64传给服务端
      // 若接口支持多图上传,可将所有base64拼接为数组格式适配字段要求
      String targetBase64 = selectedImages.first.base64Str;
      await postImage(targetBase64);
      // 提交成功提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('图片提交成功'))
      );
      // 提交成功后重置图片选择状态
      setState(() {
        images.clear();
        images.addAll(List.generate(6, (index) => "Add Image"));
      });
    } catch(e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('提交失败:$e'))
      );
    } finally {
      setState(() {
        _isUploading = false;
      });
    }
  },
),

补充注意事项

  • base64字符串体积会比原文件大33%,如果单张图片体积过大,可适当调低image_picker的imageQuality参数(如设置为30),减少传输体积
  • 若后端要求base64携带格式前缀(如data:image/jpeg;base64,xxx),在拼接传入接口的字符串时补上对应前缀即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.08 05:24:01