dart-lang / http

A composable API for making HTTP requests in Dart.
https://pub.dev/packages/http
BSD 3-Clause "New" or "Revised" License
1.02k stars 351 forks source link

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

Open emondd4 opened 1 month ago

emondd4 commented 1 month ago

Future customMultipartWithFile ( String url, String reservationId, List 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;

}

abdullahalamodi commented 1 month ago

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