Flutter Web如何将多张图片转Base64后按指定JSON格式上传至服务端
实现方案
你需要先导入dart:convert依赖,然后调整uploadimages方法的逻辑,遍历图片列表生成符合要求的键值对,编码为JSON后提交即可:
import 'dart:convert'; Future uploadimages() async { // 先判空避免空异常 if (_pickedImages == null || _pickedImages!.isEmpty) { throw Exception('未选择任何图片'); } final uploadurl = 'http://localhost:9000/api/v1/upload'; // 构造请求体Map Map<String, String> body = {}; // 遍历选中的图片,生成file1、file2格式的键值对 for (int i = 0; i < _pickedImages!.length; i++) { final image = _pickedImages![i]; // 将图片字节编码为base64字符串 String base64Str = base64Encode(image.image.bytes); // 拼接标准base64图片前缀,填入对应key body['file${i+1}'] = 'data:image/png;base64,$base64Str'; } final upload = await http.post( Uri.parse(uploadurl), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'Bearer $token', }, // application/json格式需要将Map转为JSON字符串后再传入body body: jsonEncode(body), ); if (upload.statusCode == 201) { return upload.body; } else { throw Exception('Failed'); } }
关键说明
- 原代码直接把Map传给了
body参数,Content-Type为application/json时必须传入JSON字符串,所以需要用jsonEncode处理Map结构 - 遍历图片时通过索引+1生成
file1、file2的键名,完全符合你要求的JSON结构 - 如果需要适配jpg、webp等其他图片格式,可以在取图时读取格式信息,替换前缀里的
png即可
内容的提问来源于stack exchange,提问作者Adil
相关产品推荐
相关产品推荐

