如何使用Dio在Flutter中上传多个图像/文件?

时间:2020-08-05 11:05:27

标签: flutter dio

我一直试图在Flutter中将多个图像/文件上传到后端。我正在使用Dio。 到目前为止,我还没有这样做。

我已经可以使用邮递员了。这是表格数据

Request made from Postman

这是我的代码:

    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;
  }

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

结果证明,有两种方法可以将多个文件添加到FormData。以下方法有效

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