http icon indicating copy to clipboard operation
http copied to clipboard

Converting object to an encodable object failed: Instance of 'MultipartRequest'

Open emondd4 opened this issue 1 year ago • 1 comments

Future <http.Response> customMultipartWithFile ( String url, String reservationId, List<String> titleList, List<File?> fileList ) async {

final headers = await _getMultipartHeader();

final completeUrl = _buildUrl(url);

final request = http.MultipartRequest(
  'POST',
  Uri.parse(completeUrl),
);

request.headers.addAll(headers);
request.fields.addAll({
  'reservation_id': reservationId,
  'titles[0]': "Passport"
});
print(request.fields);
for(int i=0;i<fileList.length;i++){
  if (fileList[i] != null) {
    final mimeTypeData = lookupMimeType(fileList[i]!.path)!.split('/');
    request.files.add(
      await http.MultipartFile.fromPath(
        "files[0]",
        fileList[i]!.path,
        contentType: MediaType(mimeTypeData[0], mimeTypeData[1]),
      ),
    );
  }
}

log('Checking for Post API start & end point ${json.encode(request)}');
final StreamedResponse = await request.send();
final response = await http.Response.fromStream(StreamedResponse);
return response;

}

emondd4 avatar Aug 03 '24 06:08 emondd4

hi @emondd4 If you mean send list of files, I think there is a problem in your code. it depends on how your backend will receive the object but still you need to update your code

there are two ways to handle your case based on json structure

1- send files as objects if your json structure looks like this

{
"files" : {
"0": "file_data",
"1": "file_data", 
"3": "file_data", 
          }
}

then you need to pass i to the field key like this

await http.MultipartFile.fromPath(
        "files[i]", // pass i here
        fileList[i]!.path,
        contentType: MediaType(mimeTypeData[0], mimeTypeData[1]),
      ),

or 2- send files as list (preferred) if your json structure like this

{
"files" : [
"file_data_1",
"file_data_2", 
"file_data_3",
       ]
}

then you need to update your code like this

await http.MultipartFile.fromPath(
       "files[]", // don't pass anything in []
       fileList[i]!.path,
       contentType: MediaType(mimeTypeData[0], mimeTypeData[1]),
     ),

hope this help you

abdullahalamodi avatar Aug 07 '24 01:08 abdullahalamodi

Closing as stale.

I think it was this line: json.encode(request) that was throwing because MultipartRequest does not define toJson method - but why would it?

mraleph avatar Nov 15 '24 15:11 mraleph