'How to set a different content-type for each FormData entry with Dio?

I am trying to upload an image and some extra data (JSON map) with the Dio post request. My question is how can I set content-type for each field of FormData.fromMap

final data = FormData.fromMap({
        "file": await MultipartFile.fromFile(
          path,
          filename:name,
        ),
        "mapData": {"name": "user_name"},  //I wnat to set content-type for this value
      });

How to add content-type for each FormData entry.



Solution 1:[1]

To add JSON data we can do it with MultipartFile.fromString where we can specify the content-type of the data.

import http_parser package form 'package:http_parser/http_parser.dart'; to use MediaType class.

 final data = FormData.fromMap({
    "file": await MultipartFile.fromFile(
      path,
      filename: name,
    ),
    "mapData": await MultipartFile.fromString(
      {"name": "user_name"},
      contentType: MediaType.parse('application/json'),
    ),
  },
 ListFormat.multiCompatible,
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sanjay Soni