在Flutter中上传带有http.post和注册表格的图片?

时间:2019-11-09 06:43:54

标签: http post flutter flutter-layout flutter-dependencies

所以我想将文件(图像)与一堆其他变量(字符串)上传到服务器

字符串firstname,lastname,birthDay,phone,adresse;文件图像;

return http.post(
  uri,
  headers: {
    'Accept': 'application/json',
    "Authorization": "Bearer $token",
  },
  body: body,
  encoding: encoding,
);

Future<http.Response> postRegisteration() async {
    return await api.httpPost('fotApp/master', body: {
        'firstname': 'lorem',
        'lastname': 'lorem',
        'birthDay': 'lorem',
        'adresse': 'lorem',
        'phone': 'lorem',
        'image': 'lorem'
      }).then((reponse) {
        var data = jsonDecode(reponse.body);
        print(data);
    });
}

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

在fileList中,您应该添加任何要上传的文件

    List<MultipartFile> fileList = List();
    fileList.add(MultipartFile.fromBytes(
        'documents', await filePath.readAsBytes(),
        filename: fileName));

对于其他零件参数,请使用参数映射

    Map<String, String> params = {
      "first_name": widget.mUserDetailsInputmodel.firstName,
      "last_name": widget.mUserDetailsInputmodel.lastName,
      "email": widget.mUserDetailsInputmodel.emailAddress,
    };

然后像这样发送请求

  Future<String> multipartRequest({var url, var partParams, var files}) async {
    Map<String, String> headers = {
      "X-API-KEY": X_API_KEY,
      "Accept": "application/json",
      "User-Auth-Token": authToken };
    var request = http.MultipartRequest("POST", Uri.parse(url));
    request.headers.addAll(headers);

    if (partParams != null) request.fields.addAll(partParams);// add part params if not null
    if (files != null) request.files.addAll(files);// add files if not null

    var response = await request.send();
    var responseData = await response.stream.toBytes();
    var responseString = String.fromCharCodes(responseData);
    print("responseBody " + responseString);
    if (response.statusCode == 200) return responseString;
  }