我有一个适合web, android和ios的应用程序。我已经实现了
下面的包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的解决方案?
你不能在forEach上使用async,因为它只会返回一个承诺数组,而不会等待它们。为了解决这个问题,您可以为异步函数使用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";
}