Home > OS >  How to send multiple(as a list) files in restApi in flutter with single key from form-data
How to send multiple(as a list) files in restApi in flutter with single key from form-data

Time:12-20

I want to send multiple Files(Images) in post api from flutter with single key from form-data.

Just like in the picture for "images[]" key i have multiple images to send.

enter image description here

CodePudding user response:

 var uri = Uri.parse("${baseUrl}/user/addPost");
 https.MultipartRequest request = new https.MultipartRequest('POST', uri);

 request.fields['user_id'] = "54";
 request.fields['title'] = postAdModel.title!;
 request.fields['type'] = postAdModel.type!;
 request.fields['category_id'] = postAdModel.category_id.toString();

 ////////////////////////// Thumbnail Image Adding /////////////////

 final stream = https.ByteStream(postAdModel.thumbnail!.openRead());
 stream.cast();
 final length = await postAdModel.thumbnail!.length();
 var multiport = https.MultipartFile(
      'thumbnail',  // key
       stream,
       length,
       filename: postAdModel.thumbnail!.path,
 );
 request.files.add(multiport);

 ////////////////////////*   Gallery Images Adding */////////////////////

 List<https.MultipartFile> galleryImages = <https.MultipartFile>[];

 for (int i = 0; i < postAdModel.images!.length; i  ) {
     File imageFile = postAdModel.images![i];
     var stream = new https.ByteStream(imageFile.openRead());
     stream.cast();
     var length = await imageFile.length();
     var multipartFile = https.MultipartFile(
                             "images[]",
                              stream,
                              length,
                              filename: imageFile.path);
  galleryImages.add(multipartFile);
 }
request.files.addAll(galleryImages);
var response = await request.send();
  • Related