Я создаю функцию Future для почтового запроса Multipart API с загрузкой изображения. Но когда я использую request.fields.addAll(updateProfileInfo.toJson()); он не отвечает.
Вот пример кода -
Future<Map<String, dynamic>> updateprofile(
UpdateProfileInfo updateProfileInfo, File imageFile) async {
var stream = http.ByteStream(Stream.castFrom(imageFile.openRead()));
var length = await imageFile.length();
String url = "$baseAPIUrl/update-profile-info";
String _token = await SavedData().loadToken();
String authorization = "Bearer $_token";
final body = jsonEncode(updateProfileInfo);
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
"Authorization": authorization
};
var request = http.MultipartRequest("POST", Uri.parse(url));
var multipartFile = http.MultipartFile('image', stream, length,
filename: basename(imageFile.path));
request.headers.addAll(headers);
request.files.add(multipartFile);
request.fields.addAll(updateProfileInfo.toJson());
http.StreamedResponse response = await request.send();
String respStr = await response.stream.bytesToString();
dynamic respJson;
try {
respJson = jsonDecode(respStr);
} on FormatException catch (e) {
print(e.toString());
}
print('API ${response.statusCode}\n $respJson');
bool isSuccess = response.statusCode == 200;
var data = json.decode(respStr);
return {
'isSuccess': isSuccess,
"message": isSuccess ? data["success"]["message"] : null,
"name": isSuccess ? data["success"]["name"] : null,
"classgroup": isSuccess ? data["success"]["classgroup"] : null,
"image": isSuccess ? data["success"]["image"] : null,
"error": isSuccess ? null : data['error']['message'],
};
}
Как я могу отправить запрос поля тела? пожалуйста, помогите мне
request.fields
— это карта типа <String, String>
. Таким образом, все данные ваших полей должны быть строковыми. В противном случае updateProfileInfo.toJson()
должен возвращать объект типа Map<String, String>
.
Надеюсь, это может решить вашу проблему.