在 http post flutter 中发送图像列表和数据

问题描述 投票:0回答:1

我有需要发送到后端的图像和数据(字符串)列表。 这是重要的功能:

Future MakePostPetOfferRequest(
      {required String title,
      required String description,
      required String price,
      required String city,
      required String species,
      required String sex,
      required String ageYears,
      required String ageMonths,
      required String breed,
      required List<File?> images}) async {
    Uri url = Uri.parse('http://$ip/create_sale_post');
    Map<String, dynamic> body = {
      "Title": title,
      "Description": description,
      "City": city,
      "Species": species,
      "Price": price,
      "Sex": sex,
      "Years": ageYears,
      "Months": ageMonths,
      "Breed": breed,
      "images": images,
    };

    var response = await http.post(url, headers: {"cookie": sessionCookie}, body: body);
    if (response.headers['set-cookie'] != null) {
      String initSessionCookie = response.headers['set-cookie']!;
      if (sessionCookie != "") sessionCookie = initSessionCookie.substring(0, initSessionCookie.indexOf(";"));
    }
    return response;
  }

但是我遇到了不同的错误,第一个是错误:

类型“List”不是类型 cast 中类型“String”的子类型

我也不确定如何将图像添加到一个字段中,就像我在 Post man 上所做的那样:

希望问题清楚,感谢您的帮助。

flutter image http post
1个回答
0
投票

要发布图片,您应该使用表单数据。

import 'package:dio/dio.dart' as formDataMap;

formDataMap.FormData formData = formDataMap.fromMap({
        "Title": title,
      "Description": description,
      "City": city,
      "Species": species,
      "Price": price,
      "Sex": sex,
      "Years": ageYears,
      "Months": ageMonths,
      "Breed": breed
      });
      for (var file in images) {
        formData.files.addAll([
          MapEntry("images[]",
              await formDataMap.MultipartFile.fromFile(file.path)),
        ]);
      }
© www.soinside.com 2019 - 2024. All rights reserved.