4

I want to send a File with a complex JSON object containing JSON Array. How can I do it? enter image description here

I want to send this kind of FormData. Here is how I have implemented it:

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);

}

1
  • Your question lacks information on what happened vs what you expected to happen (or in other words, what is the exact problem). Answering to such questions is a guesswork because the answer may address a problem unrelated to your issue. Commented Jan 15, 2021 at 12:36

5 Answers 5

6

https://github.com/flutterchina/dio/issues/1155#issuecomment-842492719

Another method would be using the ListFormat.multiCompatible param in FormData.

And I believe this will work on nested arrays without changing the structure of your body, encoding or adding [] to the keys: e.g.

FormData.fromMap(data, ListFormat.multiCompatible); // <-- add this
Sign up to request clarification or add additional context in comments.

Comments

5

Currently you are using urlEncoded to encode whole data map, which isn't what you want. If you want to encode a specific part of request using a different serialization method, you have to do it manually:


final data = {
  // urlEncoded fields
  // ...
  "bankDetails": jsonEncode([
    {"name": "ASD", "acc": "123"},
  ]),
};

//...
data: FormData.fromMap(data)

Comments

2

Remember to add "[]" after the key. Simplest Method to send array in form 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) + '%');
    }
  },
);

1 Comment

You just saved me after hours of search!!
1

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()));

Comments

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,
  );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.