【问题标题】:send image and text at the same time flutter同时发送图像和文本
【发布时间】:2021-03-17 00:21:13
【问题描述】:

我想同时使用 HTTP post 方法上传图像和其他类型的数据,如字符串和整数。但我得到错误代码说 json 无法编码图像文件,我在颤振上有这个代码:

static Future<ApiReturnValue<Asset>> addAsset(Asset asset, File imageFile,
  {http.Client client}) async {
client ??= http.Client();

String url = baseUrl + 'asset';
var uri = Uri.parse(url);

var response = await client.post(
  uri,
  headers: {
    "Content-type": "application/json",
    "Authorization": "Bearer ${User.token}"
  },
  body: jsonEncode(
    <String, dynamic>{
      "name": asset.name,
      "condition": asset.condition,
      "purchase_date": asset.purchaseDate,
      "price": asset.price,
      "location": asset.location,
      "description": asset.description,
      "image": imageFile,
    },
  ),
);

if (response.statusCode != 200) {
  return ApiReturnValue(message: "Add item failed, please try again");
}

var data = jsonDecode(response.body);

Asset value = Asset.fromJson(data['data']['asset']);
return ApiReturnValue(value: value);

}

有什么方法可以同时在 HTTP 发布请求上发送图像和文本,而无需使用多部分请求分离图像?

【问题讨论】:

  • 嗨,有趣的是,也许对图像进行 base64 编码,以便它可以嵌入到 json 中?不会像单独发送它那样有效。
  • 好的,我试试,谢谢

标签: flutter


【解决方案1】:

要在 POST 的请求正文中包含图像,通常您必须将其转换为多部分文件,然后将其作为 formdata 包含在正文中。这要求服务器在从客户端接收图像时,需要在 formdata 本身中包含多部分文件。

我想为你推荐这个包名dio。它支持 MultipartFile、FormData 和其他强大的辅助类。

这是一个例子:

static Future<bool> sendImage(String imagePath) async {
    try {
      final content = MultipartFile.fromFile(imagePath);
      final contentType = 'multipart/form-data';
      final Response response = await dio.post('$BASE_URL/$images',
          data: FormData.fromMap({'file': content}),
          options: Options(contentType: contentType));
      if (response.statusCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      return null;
    }
  }

您可以在此处阅读更多关于FormData 的信息

【讨论】:

    【解决方案2】:

    您可以在请求标头中包含您的资产数据:

      var response = await client.post(
        uri,
        headers: {
          "Content-type": "application/json",
          "Authorization": "Bearer ${User.token}",
          "asset-data": jsonEncode(
            <String, dynamic>{
              "name": asset.name,
              "condition": asset.condition,
              "purchase_date": asset.purchaseDate,
              "price": asset.price,
              "location": asset.location,
              "description": asset.description
            },
          ),
        },
        body: imageFile.readAsBytesSync(),
      );
    

    这将需要您修改服务器端代码以从标头中读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      • 2020-07-19
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多