0

I am trying to create a http.post request that sends an image file along with text. I think that I am only sending a partial request to the server and its getting rejected. I have tried this in MultiPartForm and in the method below

I have tried to create the post request but, I get this error: Unhandled Exception: type '_File' is not a subtype of type 'String' in type cast

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

I want to create this request and verify that I data is accepted by my server.

  • Possible duplicate of [HTTP POST with Json on Body - Flutter/Dart](https://stackoverflow.com/questions/50278258/http-post-with-json-on-body-flutter-dart) – diegoveloper May 01 '19 at 03:59
  • Possible duplicate of [Flutter: http post upload an image](https://stackoverflow.com/questions/49125191/flutter-http-post-upload-an-image) – Richard Heap May 01 '19 at 10:19

1 Answers1

1

What you can do is to convert your file(image) to base64 and upload it as string example:

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

Then decode it in you server.

Taym95
  • 2,331
  • 13
  • 14