【问题标题】:Using Http Post to upload a Body of Text in FlutterFlutter 中使用 Http Post 上传正文
【发布时间】:2019-09-19 16:52:17
【问题描述】:

我正在尝试创建一个发送图像文件和文本的 http.post 请求。我认为我只是向服务器发送了部分请求并且它被拒绝了。我已经在 MultiPartForm 和下面的方法中尝试过这个

我已尝试创建发布请求,但出现此错误:未处理的异常:类型“_File”不是类型转换中“字符串”类型的子类型

void createPreferences(
    String phone,
    String nickName,
    String customerType,
    double age,
    File currentSelfie) {
  //Variables

  var uri = Uri.http('10.0.2.2:8000', '/api/customer/create_customer_details/', params);

  var params = {
    'access_token': _accessTkn,
  };


  final Map<dynamic, dynamic> custPreferences = {
    'phone': phone,
    'nick_name': nickName,
    'customer_type': customerType,
    'age': '${'age'}',
  };





     var request =  http.MultipartRequest("POST", uri,);
 var multipartFile = new http.MultipartFile('current_selfie', stream, length,
          filename: basename(currentSelfie.path));


  request.files.add(multipartFile);

      var response = await request.send();
      print(response.statusCode);
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });
    }


    final Map<String, dynamic> responseData = json.decode(response.body);
    print(responseData);
    print('Response body: ${response.body}');
  });
}

我想创建这个请求并验证我的数据是否被我的服务器接受。

【问题讨论】:

标签: flutter http-post


【解决方案1】:

您可以做的是将您的文件(图像)转换为 base64 并将其作为字符串示例上传:

import 'dart:convert';

void createPreferences(
    String phone,
    String nickName,
    String customerType,
    double age,
    File currentSelfie) {
  //Variables

  var url = 'http://10.0.2.2:8000/api/create_customer_details/?';

  final Map<dynamic, dynamic> custPreferences = {
    'phone': phone,
    'nick_name': nickName,
    'customer_type': customerType,
    'age': '${'age'}',
    'current_selfie': base64Encode(currentSelfie.readAsBytesSync()),
    'access_token': _accessTkn,
  };



  http.post(url, body: custPreferences, headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  }).then((http.Response response) {
    print(response);

    final Map<String, dynamic> responseData = json.decode(response.body);
    print(responseData);
    print('Response body: ${response.body}');
  });
}

然后在你的服务器中解码它。

【讨论】:

  • 我收到此错误:无法将参数类型“文件”分配给参数类型“列表”.dart(argument_type_not_assignable)
  • 感谢更新,但现在它只是抛出另一个错误:未处理的异常:FormatException:意外字符(在第 2 行,第 1 个字符)
猜你喜欢
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
  • 2021-11-11
  • 2020-01-24
相关资源
最近更新 更多