Search code examples
apiflutterhttpmultipart

Flutter : Multipart File request not working


I want to upload image by multipart File request. With using this code When I pass two image files then it's working fine. But when I want to pass one image file and another is null then it's not working. where is the problem? How can I solve this ?

Here is my code -

Future<Map<String, dynamic>> updateprofile(
      UpdateProfileInfo updateProfileInfo,
      File imageFile,
      File signatureFile) async {

    String url = "$baseAPIUrl/update-profile-info";
    String _token = await SavedData().loadToken();
    String authorization = "Bearer $_token";

    final headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      "Authorization": authorization
    };

    var request = http.MultipartRequest("POST", Uri.parse(url));

    request.headers.addAll(headers);
    request.fields.addAll(updateProfileInfo.toJson());

    request.files
        .add(await http.MultipartFile.fromPath('image', imageFile.path));
    request.files.add(
        await http.MultipartFile.fromPath('signature', signatureFile.path));

    print(" Update Profile Json ${updateProfileInfo.toJson()}");
    print("Request Fields ${request.fields}");
    http.StreamedResponse response = await request.send();

    String respStr = await response.stream.bytesToString();
    dynamic respJson;

    try {
      respJson = jsonDecode(respStr);
    } on FormatException catch (e) {
      print(e.toString());
    }

    print('API ${response.statusCode}\n  $respJson');

    bool isSuccess = response.statusCode == 200;
    var data = json.decode(respStr);

    return {
      'isSuccess': isSuccess,
      "message": isSuccess ? data["success"]["message"] : null,
      "name": isSuccess ? data["success"]["name"] : null,
      "classgroup": isSuccess ? data["success"]["classgroup"] : null,
      "image": isSuccess ? data["success"]["image"] : null,
      "error": isSuccess ? null : data['error']['message'],
    };
  }

Here is postman Screenshot

1.

enter image description here

2. POSTMAN Generated code for Dart - http

enter image description here


Solution

  • when one of your file is null, you should avoid adding it to the request body.

    if(imageFile != null){
        request.files
            .add(await http.MultipartFile.fromPath('image', imageFile.path));
    }
    if(signatureFile != null){
    request.files.add(
            await http.MultipartFile.fromPath('signature', signatureFile.path));
    }
    

    its because signatureFile.path is going to cause an error here