我想发送一个带有包含 JSON 数组的复杂 JSON 对象的文件。我该怎么做?
我想发送这种FormData。 这是我的实现方式:
final data = {
"id": 60,
"first_name": "Amit",
"last_name": "Sharma",
"email": "[email protected]",
"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);
}
https://github.com/flutterchina/dio/issues/1155#issuecomment-842492719
另一种方法是使用
ListFormat.multiCompatible
中的 FormData
参数。
我相信这将适用于嵌套数组,而无需改变你的身体结构,编码或添加
[]
到键:例如
FormData.fromMap(data, ListFormat.multiCompatible); // <-- add this
目前您正在使用
urlEncoded
来编码整个 data
地图,这不是您想要的。如果您想使用不同的序列化方法对请求的特定部分进行编码,则必须手动执行:
final data = {
// urlEncoded fields
// ...
"bankDetails": jsonEncode([
{"name": "ASD", "acc": "123"},
]),
};
//...
data: FormData.fromMap(data)
记住在密钥后面添加“[]”。以表单数据发送数组的最简单方法:
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) + '%');
}
},
);
final dio = Dio();
dio.options.headers = {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
};
FormData formData = new FormData();
formData = FormData.fromMap({
"[bankDetails][]": [ {"name": "ASD", "acc": "123"},
{"name": "ASDFG", "acc": "1234"} ] });
final responseJson = await dio.post(
url,
data: formData,
);
all the above are not right i will explain you how you can do it
Future<void> postPropertyAPI(BuildContext context, String projectColonyName) async {
var typeOfProperty = "";
if(widget.type == AppStrings.plots){
typeOfProperty = plotTypeProperty;
}else if(widget.type == AppStrings.commercialSpace){
typeOfProperty = commercialTypeProperty;
}else if(widget.type == AppStrings.flatHouseVilla){
typeOfProperty = flatHouseTypeProperty;
}
Loader.ProgressloadingDialog(context, true);
try {
const url = Urls.postPropertyUrl;
var formData = FormData.fromMap({
"user_id": userID,
"calony_name": projectColonyName,
"type_of_property": typeOfProperty,
// "location[0]": location,
"address": propertyAddressController.text,
"width": widthController.text,
"length": lengthController.text,
"totalarea": totalAreaController.text,
"facing": facing,
"open_side": openSide,
"transaction_type": transactionType,
"possession_status": possessionStatus,
"expected_price": expectedPriceController.text,
"price_per_square": pricePerSqFtController.text,
// "aminities": selectedAmenitiesList,
"description_details": descriptionController.text,
"buildup_area": superBuildupAreaController.text,
"floor_no": totalNoOfFloorsController.text,
"your_space_in_which_floor": floor,
"furnished_status": furnished,
"floor_no": noOfFloor,
"flat_size": flatSize,
});
formData.fields.add(MapEntry("location[]", location));
selectedAmenitiesList.forEach((amenity) {
formData.fields.add(MapEntry("aminities[]", amenity));
});
final responseDio = await Dio().post(url,data: formData,);
Loader.ProgressloadingDialog(context, false);
if (responseDio.statusCode == 200) {
print(url);
Map<String, dynamic> map = (responseDio.data as Map).cast<String, dynamic>();
PostPropertyModel response = PostPropertyModel.fromJson(map);
Utilities().toast(response.message);
if (response.status == true) {
Navigator.of(context).pop();
setState(() {});
}
}
} catch (e) {
Loader.ProgressloadingDialog(context, false);
Utilities().toast('error: $e');
}
return;
}
i want to send location and aminities in array format so dont need any changes in anywhere just do it like
formData.fields.add(MapEntry("location[]", location));
selectedAmenitiesList.forEach((amenity) {
formData.fields.add(MapEntry("aminities[]", amenity));
});
for example selectedAmenitiesList is List<String> selectedAmenitiesList = ["one", "two", "three", "four"] so all are string and MapEntry() is exept only string as a socond args so one more thing you can do like
formData.fields.add(MapEntry("aminities[]", amenity.toString()));