Flutter中如何在POST的Multipart请求中将图片文件作为HTTP body参数传递
Multipart上传图片代码修正方案
你现有代码的核心上传逻辑没有问题,只需要修复几个细节漏洞即可正常使用:
现有问题梳理
- 没有对
image做空判断,可能触发空安全异常 - 没有读取响应的返回内容,直接使用未赋值的
jsonResponse会导致崩溃 - 手动读取文件字节的方式可优化,不需要额外做IO操作
修正后的完整代码
import 'package:http_parser/http_parser.dart'; // 必须导入该依赖处理MediaType Future<void> SaveCustomTestBooking() async { var jsonResponse; // 先判断图片非空再执行请求 if (EncUserId.isNotEmpty && image != null) { var postUri = Uri.parse("http://myAPIstomTestBooking"); var request = http.MultipartRequest('POST', postUri); // 普通文本参数 request.fields['VisitDate'] = '_selectedDate'; request.fields['EncUserId'] = 'EncUserId'; // 正确添加图片文件参数,推荐使用fromPath方法简化操作 request.files.add(await http.MultipartFile.fromPath( "UserFile", // 此处替换为服务端约定的图片接收字段名 image!.path, filename: "Image.jpg", // 也可以从原路径提取真实文件名 contentType: MediaType('image', 'jpg'), )); // 发送请求并处理响应 var response = await request.send(); if (response.statusCode == 200) { // 读取响应内容解析为json var respStr = await response.stream.bytesToString(); jsonResponse = json.decode(respStr); print("Uploaded!"); Navigator.push( context, MaterialPageRoute( builder: (context) => DieticianAfterDateSelectPage( rresponse: DieticianEncBookingIdModel.fromJson(jsonResponse), ), ), ); } else { ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text("Something went wrong"))); throw Exception("Failed to fetch"); } } }
额外说明
- 如果服务端要求传base64格式的图片,不需要使用MultipartFile,直接把你提前生成的
fileContentBase64当做普通文本参数放在request.fields里即可 - 如果你要保留原本的
fromBytes写法也可以正常运行,注意保证文件读取操作在异步中执行即可
内容的提问来源于stack exchange,提问作者Toujo
相关产品推荐
相关产品推荐

