Flutter - How to send multiple images in formdata

5.4k Views Asked by At

I want to upload multiple images in flutter using dio and formData. What I did is I created a for loop for storing MultipartFile in an array and then I passed the array to the data of "img[]". However, I cannot upload the image if I passed the array but it works perfectly fine if I upload a single image.

Here's my code.

 var arr = new List(3);
 
 for (var i=0; i <_tryPath.length; i++) {
    arr[i] = await MultipartFile.fromFile(imageFile[i].path, filename: 
    imageFile[i].path.split('/').last, contentType: new MediaType('image','jpg'));
 };

 print('this is arr = $arr');

 FormData formData = new FormData.fromMap({
    "name": "Max",
    "location": "Paris",
    "age": 21,
    "img[]": arr,
 });

 // dio is in another class here in AuthService.
 AuthService().donateRegister(formData).then((val) async {
    print('successful');
    print(val.data);
 });

Can you help me uploading many images in formData? I also would like not to limit the MediaType. What will I do if I will also upload pdf/docu or jpg MediaType? I will appreciate your time and answer. Thank you!

2

There are 2 best solutions below

5
On BEST ANSWER

You can use a for loop to set image lists as show below

here I'm using multi_image_picker

 Future<int> addMultiImage({MyData myData, List<Asset> files}) async {
    var formData = FormData.fromMap({
     "name": "Max",
    "location": "Paris",
    "age": 21,
    });
    for (int i = 0; i < files.length; i++) {
      var path = await FlutterAbsolutePath.getAbsolutePath(files[i].identifier);
      formData.files.addAll([
        MapEntry("img", await MultipartFile.fromFile(path, filename: path))
      ]);
    }

    Response response = await dioHelper.post(
      "myPaths",
      queryParameters: {
       
      },
      data: formData,
    );
1
On

You can use mime package to get mime type.

import 'package:path/path.dart' as path;
import 'package:mime/mime.dart';

String getFileName(String _path){
    return path.basename(_path) 
}

FilePickerResult? result = await FilePicker.platform.pickFiles(
  allowMultiple: true,
  type: FileType.custom,
  allowedExtensions: ['jpg', 'pdf', 'doc'],
);

if(result != null) {
   List<MultipartFile> files = result.paths.map((path) => 
     MultipartFile.fromFileSync(
        path, 
        filename: getFileName(path),
        contentType: MediaType(
            lookupMimeType(getFileName(path)).split('/')[0],
            lookupMimeType(getFileName(path)).split('/')[1],
        ),
   )
).toList();  
   var dio = Dio();
   var formData = FormData.fromMap({
    'name': 'wendux', // other parameter may you need to send
    'age': 25, // other parameter may you need to send
    'files': files,
  });

  var response = await dio.post('url', data: formData); 
  // check response status code
  if(response.statusCode == 200){
     // it's uploaded
  }

} else {
   // User canceled the picker
}