How to upload multiple images/files in Flutter using Dio?

Viewed 8794

I have been trying to upload multiple images/files to the backend in Flutter. I am using Dio. So far, I have not been able to do so.

I have been able to do so using postman. This is the form-data

Request made from Postman

This is my code:

    Future<dynamic> fileUpload(List<String> filepath, String url) async {
    var token = await storage.getToken();
    var idToken = await storage.getIdToken();
    Dio dio = Dio();

    List uploadList = [];
    for (var file in filepath) {
      var multipartFile = await MultipartFile.fromFile(
        file
      );
      uploadList.add(multipartFile);
    }

    FormData formData = FormData.fromMap({"assignment": uploadList});
     var response = await dio.post(APIURL.baseUrl + url,
        data: formData,
        options: Options(headers: {
          HttpHeaders.authorizationHeader: "Bearer $token",
          'idToken': idToken,
        }));
    return response;
  }

Can somebody please help.

3 Answers

Turns out there are two ways to add multiple files to FormData. The following approach worked

var formData = FormData();
for (var file in filepath) {
  formData.files.addAll([
  MapEntry("assignment", await MultipartFile.fromFile(file)),
]);
}

This works as well:

var formData = FormData();
for (var file in filepath) {
  formData.files.add(MapEntry("assignment", 
  MultipartFile.fromFileSync(file)));
}
final httpDio = Dio();
  final formData = dio.FormData.fromMap({
    "data": "{}",
    "File": await dio.MultipartFile.fromFile(
        filePath,
        filename: filePath.toString().split("/").last,
        contentType: MediaType('image', 'jpg'),
      ),
    "type": "image/jpg"
  });

final dio.Response response = await httpDio.post(
      Strings.baseUrl +"/"+ Strings.documentUpload,
      data: formData,
      options: dio.Options(
        headers: {
          "RequestVerificationToken": box.read(Keys.token),
          "Content-Type": "multipart/form-data"
         }
        )
      );
Related