Error sending Multipart request using Dio package: Flutter

19 views Asked by At

I am working on an application in which I want to implement a feature to save image+json data. For this purpose, I am using the Dio package in Flutter.
The request is sent as (as tested in postman)-
enter image description here
Now, to achieve the same, I wrote the following method-

Future<int> saveComplaint({
    required String complaintSubject,
    required String complaintDescription,
    required String complaintPriority,
    required String categoryToken,
    required int pinCode,
    required String address,
    required String wardNo,
    required int contactNo,
  }) async {
    try {
      String? accessToken = await _secureStorage.readAccessToken();
      String? userToken = await _secureStorage.readUserToken();
      Options options = Options(
        validateStatus: (_) => true,
        contentType: Headers.multipartFormDataContentType,
        responseType: ResponseType.json,
        headers: {HttpHeaders.authorizationHeader: bearerPrefix + accessToken!},
      );

    List<dio.MultipartFile> files=[];
      for (int i = 0; i < images.length; i++) {
        XFile image = images[i];
        files.add(await dio.MultipartFile.fromFile(
          image.path,
          filename: 'image_$i.jpg',
        ));
      }


      Map<String, dynamic> complaintData = {
        'complaintSubject': complaintSubject,
        'complaintDescription': complaintDescription,
        'complaintPriority': complaintPriority,
        'categoryToken': categoryToken,
        'pincode': pinCode.toString(),
        'address': address,
        'wardNo': wardNo,
        'contactNo': contactNo.toString(),
        'userToken': userToken ?? '',
      };



      dio.FormData formData=dio.FormData.fromMap({
        "complaintData": complaintData,
        "images:": files
      });



      dio.Response response = await _dio.post(saveComplaintUrl, data: formData,options: options);
      log('Response data: ${response.data}');
      Map<String, dynamic> responseData = response.data;
      if(responseData.isNotEmpty){
        return responseData['code'];
      }
    } catch (err) {
      log('$err');
      debugPrintStack();
    }
    return -1;
  }

Now, when I make the request, I get an error on backend (Spring Boot):

2024-03-10T12:58:44.275+05:30  WARN 7848 --- [mcat-handler-76] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required part 'complaintData' is not present.]

Now, I have successfully tested the API on Postman, but getting an error in Flutter. Please help me figure out what is wrong in my multipart request. I have checked out this article-
https://blog.logrocket.com/networking-flutter-using-dio/

0

There are 0 answers