使用 MultipartFile 将 XFile 图像发送到 API - Flutter

Posted

技术标签:

【中文标题】使用 MultipartFile 将 XFile 图像发送到 API - Flutter【英文标题】:Sending XFile image to API using MultipartFile - Flutter 【发布时间】:2021-07-28 09:35:25 【问题描述】:

我有一个适用于 web、androidios 的应用程序。 我已经实现了下面的包

https://pub.dev/packages/image_picker/example

image_picker:^0.8.2 image_picker_for_web: ^2.1.1

任务:

    用户需要选择多个图像(通过 android 调试时,我有时会收到 websocket 连接预期,并且应用程序退出时没有任何错误消息。如果您也能够对此问题提供一些见解,则奖励)

    点击提交上传图片(XFile)到API

class UserAttachments 
  List<XFile>? attachments = [];
  int userID = 0;


Future<String> submitImage(UserAttachments ua) async 
  http.MultipartRequest request =
      new http.MultipartRequest("POST", Uri.parse(kAttachmentsURI));

  Map<String, String> headers = "Content-Type": "application/json";

  ua.attachments!.forEach((element) async 
    var bytes = element.readAsBytes();
    request.files.add(new http.MultipartFile.fromBytes('file', await bytes));
  );

  request.headers.addAll(headers);
  request.fields['userID'] = '23';

  http.StreamedResponse responseAttachmentSTR = await request.send();

  print(responseAttachmentSTR.statusCode);
  return "SENT"; // + "  - Respomse:  " + map.toString();


上面的代码似乎不起作用。有适合 web/android/ios 的解决方案吗?

【问题讨论】:

您好,您的问题需要更具体一些。这里的确切问题是什么? 嗨,我似乎无法将文件传递给 api,返回一般错误 500。 【参考方案1】:

您不能在 forEach 上使用 async,因为这只会返回一组 Promise 而不会等待它们。要解决此问题,您可以将 for loop 用于异步函数。

for(var i = 0; i < ua.attachments!.length; i++) 
  var element = ua.attachments[i];
  var bytes = element.readAsBytes();
  request.files.add(new http.MultipartFile.fromBytes('file', await bytes));

你可以使用Future.wait优化这段代码

Future<String> submitImage(UserAttachments ua) async 
      http.MultipartRequest request =
          new http.MultipartRequest("POST", Uri.parse(kAttachmentsURI));
    
      Map<String, String> headers = "Content-Type": "application/json";
    
      var bytes = await Future.wait(ua.attachments!.map((el) => el.readAsBytes()));
      request.files.addAll(bytes.map((b) => new http.MultipartFile.fromBytes('file', b)));
    
      request.headers.addAll(headers);
      request.fields['userID'] = '23';
    
      http.StreamedResponse responseAttachmentSTR = await request.send();
    
      print(responseAttachmentSTR.statusCode);
      return "SENT";

【讨论】:

从 API 收到 500 我检查了图片的 url 路径 - localhost:59934/47aab53a-2889-4d65-9793-216693a248b8 这可能会导致问题吗?

以上是关于使用 MultipartFile 将 XFile 图像发送到 API - Flutter的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Flutter 中将 XFile 转换为文件

使用 Angular2 将 MultipartFile 作为请求参数发送到 REST 服务器

在 Spring 中使用 RestTemplate 作为请求参数的 MultipartFile + String

怎么把 File 类型转 MultipartFile

Spring rest 控制器“MultipartFile[] multipartFile”总是接收 [] 或 null 文件

怎么将一段字符转换成MultipartFile