I create a Future function for Multipart API post request with upload image. But when I use request.fields.addAll(updateProfileInfo.toJson()); it's not responding.
Here is the code sample -
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'],
};
}
How can I send body field request ? please someone help me
request.fields
is a map of type <String, String>
. So all of your fields data must be string. In other way updateProfileInfo.toJson()
must return Map<String, String>
type object.
Hope this might solve your issue.