jsonflutterdartpostman

Sending file to API in flutter


I'm trying to send a file from flutter app to API. This API accept values as follows:

enter image description here

Here profileImage accepts type File

This is the code I used in flutter:

                      ....................
                      ....................

                      final File _imgfile = widget.imageFile;

                      print(_fbName + _fbEmail);

                      final body = {
                        "name": _fbName,
                        "gender": gender,
                        "bday": bday,
                        "email": _fbEmail,
                        "phone": _phone,
                        "profileImage": _imgfile
                      };
                      print(body);

                      RegisterUserService.RegisterUser(jsonEncode(body))
                          .then((success) {
                        if (success) {
                          print('registration successfull');

                          //passing data to next screens
                          Navigator.of(context).push(MaterialPageRoute(
                              builder: (context) => SetupStepThree()));
                        } else {
                          print('registration error !');
                        }
                      });
                      ..................

And this is the service called by above code

class RegisterUserService {
  static Future<bool> RegisterUser(body) async {

    final response =
        await http.post('${URLS.BASE_URL}/user/register', body:body);

    var data = response.body;
    // print(body);
    print(json.decode(data));

    // Map<String, dynamic> res_data = jsonDecode(data);
    // log(res_data['loginstatus']);
    // if (res_data['loginstatus'] == 'olduser') {
    //   return true;
    // } else {
    //   return false;
    // }
    return false;
  }
}

But the thing is this gives me the following error.

**

I/flutter ( 4860): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 4860): The following JsonUnsupportedObjectError was thrown while handling a gesture:
I/flutter ( 4860): Converting object to an encodable object failed: Instance of '_File'

**

I want to know what's wrong with this code and how can I pass an image to this endpoint


Solution

  • In order to upload files in flutter you can use MultipartRequest

    Uri uri = Uri.parse("${URLS.BASE_URL}/user/register");
    var fileStream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
      var length = await imageFile.length();
    
    var request = new http.MultipartRequest("POST", uri);
    //add your fields here
    request.fields.add("gender","male");
    request.fields.add("name","sssss");
    
    var multipartFile = new http.MultipartFile('file', fileStream, length,
          filename: <Your file name>);
    request.files.add(multipartFile);
      var response = await request.send();
     //do whatever you want with the response
    

    Let me know if this solves your problem