首页 > 解决方案 > 如何使用 Dio 包在 Flutter 中的 formdata 中发送数组?

问题描述

我想发送一个包含 JSON 数组的复杂 JSON 对象的文件。我该怎么做? 在此处输入图像描述

我想发送这种 FormData。这是我实现它的方式:

final data = {
  "id": 60,
  "first_name": "Amit",
  "last_name": "Sharma",
  "email": "j.purohit198@gmail.com",
  "phone_no": "1111111111",
  "addr": "Lko",
  "status": "VERIFIED",
  "total_funds": 0,
  "bankDetails": [
    {"name": "ASD", "acc": "123"},
    {"name": "ASDFG", "acc": "1234"}
  ]
};
if (file != null) {
  data['pic'] =
      MultipartFile.fromFileSync(file.path, filename: 'profile_image');
}
final formData = FormData.fromMap(data);

final formData = FormData.fromMap(data);

final res = await _dio
    .post(
      '$kBaseUrl$kUploadPlanterStory',
      options: Options(
        headers: headers,
        contentType: Headers.formUrlEncodedContentType,
      ),
      data: formData,
    )
    .catchError((e) => throw getFailure(e));

print(res);

}

标签: flutterdartdio

解决方案


请记住在键后添加“[]”。以表单数据发送数组的最简单方法:

FormData formData = new FormData.fromMap({
  "name": "Max",
  "location": "Paris",
  "age": 21,
  "image[]": [1,2,3],
});

Response response = await dio.post(
  //"/upload",
  "http://143.110.244.110/radius/frontuser/eventsubmitbutton",
  data: formData,
  onSendProgress: (received, total) {
    if (total != -1) {
      print((received / total * 100).toStringAsFixed(0) + '%');
    }
  },
);

推荐阅读