【问题标题】:How to set a different content-type for each FormData entry with Dio?如何使用 Dio 为每个 FormData 条目设置不同的内容类型?
【发布时间】:2022-07-08 18:29:42
【问题描述】:

我正在尝试使用 Dio 发布请求上传图像和一些额外数据(JSON 映射)。我的问题是如何为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
      });

如何为每个 FormData 条目添加内容类型。

【问题讨论】:

    标签: flutter dart multipart dio


    【解决方案1】:

    要添加 JSON 数据,我们可以使用 MultipartFile.fromString 来完成,我们可以在其中指定数据的 content-type。

    导入http_parser 封装形式'package:http_parser/http_parser.dart'; 以使用MediaType 类。

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

    【讨论】:

      【解决方案2】:

      您也需要在发送数据之前对数据进行 json 编码,这里:

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

      【讨论】:

        猜你喜欢
        • 2019-06-28
        • 2014-05-25
        • 2022-08-02
        • 1970-01-01
        • 2020-12-15
        • 1970-01-01
        • 1970-01-01
        • 2015-08-29
        • 2016-09-28
        相关资源
        最近更新 更多