Upload image with http.post and registration form in Flutter?

假如想象 提交于 2020-01-10 05:38:05

问题


so i want to upload a File (image) to a server with a bunch of other variable (Strings)

String firstname , lastname , birthDay, phone , adresse ; File image;

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:


Try something like this

In fileList, you should add any file you like to upload

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

For other part parameters use params map

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

Then send request somthing like this

  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;
  }



来源:https://stackoverflow.com/questions/58777053/upload-image-with-http-post-and-registration-form-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!