3

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 Answers 2

5

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,
    );
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the help! That logic enlightened me. I just have 1 question, If the file is a jpg, png, document, or pdf, how am I supposed to add those files corresponding to its type?
inside asset ,you can just use as files List<File> files, through the file path in the filename you do get the fle extension
Hi! what should I do if the image is null?
just leave it empty, but ideally when sending data here List<File> files do verify its correct
hello @griffins, can you please check this question also? It's about uploading assets using multi_image_picker. Thank you so much! stackoverflow.com/questions/68799984/…
3

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
}

1 Comment

Thanks for that infoo! It did help me get the file type :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.