如何解决无法在flutter android应用程序中上传多个图像
我正在尝试使用使用 Flutter 语言构建的 android 应用程序在服务器中上传多个图像。这是我正在尝试的代码。
static Future postDataWithFile(......List<File> images) async {
Map<String,String> headers = {
"Accept": "application/json",'Content-Type': 'application/json; charset=UTF-8','Authorization': 'Bearer $token',};
var request = http.MultipartRequest('POST',Uri.parse(url));
request.headers.addAll(headers);
request.fields['contact'] = insertVisitedPlace.contact;
request.fields['ownerName'] = insertVisitedPlace.ownerName;
request.fields['orgName'] = insertVisitedPlace.orgName;
request.fields['orgtype'] = insertVisitedPlace.orgType.toString();
request.fields['nextFollowup'] = insertVisitedPlace.nextFollowup ?? "";
..............................
这里我使用一个列表来存储所有图像。
List<MultipartFile> allImagesAfterConvert = [];
images.forEach((image) {
allImagesAfterConvert.add(
await http.MultipartFile.fromPath(
'orgImages',image.path,)
);
});
向服务器发送添加所有图像的请求。但是在服务器中只能获得一张图像。
request.files.addAll(allImagesAfterConvert);
try {
final response = await request
.send()
.timeout(Duration(seconds: timeoutSeconds),onTimeout: () {
throw TimeoutException("Connection time out. Please try again");
});
return _isValidResponse(response) ? response : _error(response);
} on SocketException {
throw Failure("No Internet Connection");
} on TimeoutException {
throw Failure("Request time out");
} on Error catch (e) {
throw Failure(e.toString());
}
}
解决方法
将 orgImages 替换为 orgImages[]
images.forEach((image) {
allImagesAfterConvert.add(
await http.MultipartFile.fromPath(
'orgImages[]’,image.path,)
);
});
这应该有效。