如何使用Dio将多个图像上传到服务器?

时间:2020-11-04 16:11:21

标签: flutter dart

CreatePostImage(String author,List<File> images) async {
  try {
    String imagename;
    FormData formData = new FormData.fromMap({
      'author' : author.toString(),
      'MediaImageArray': [
        for (var i = 0; i < images.length; i++) {imagename = images[i].path.split('/').last,
          await MultipartFile.fromFile(images[i].path, filename: imagename), }
      ]});
 
    Response response = await Dio().post("$SERVER_IP/api/articles/", data: formData);
    print(response.toString());
  } catch (e) {
    print(e);
  }
}

我尝试了这段代码,但是它向服务器发布了空值。是否知道解决方案?

更新

{"id":"bb1936af-01ad-4873-ad14-7dc3aedee632","author":"d39d29c8-4807-41c5-a3fa-e9cb117fdb2d","MediaImageArray":null}

这是我得到的输出。

1 个答案:

答案 0 :(得分:0)

docs

FormData.fromMap({
    "files": [
      MultipartFile.fromFileSync("./example/upload.txt",
          filename: "upload.txt"),
      MultipartFile.fromFileSync("./example/upload.txt",
          filename: "upload.txt"),
    ]
  });

因此,您的情况将是这样的:

CreatePostImage(String author,List<File> images) async {
  try {
    String imagename;
    FormData formData = new FormData.fromMap({
      'author' : author.toString(),
      'MediaImageArray': images.map((item)=> MultipartFile.fromFileSync(item.path,
          filename: item.path.split('/').last)).toList()
});
 
    Response response = await Dio().post("$SERVER_IP/api/articles/", data: formData);
    print(response.toString());
  } catch (e) {
    print(e);
  }
}