Skip to content

Instantly share code, notes, and snippets.

@saiponethaaung
Created November 18, 2020 12:20
Show Gist options
  • Save saiponethaaung/251ba170b0c2cd5b5e01ee42270a5215 to your computer and use it in GitHub Desktop.
Save saiponethaaung/251ba170b0c2cd5b5e01ee42270a5215 to your computer and use it in GitHub Desktop.
Flutter File upload with http
Future<http.MultipartRequest> httpPostWithFile({
url,
header,
}) async {
Map<String, String> finalHeader = {};
var token = await this.retrieveToken();
if (token != null && token.isNotEmpty) {
finalHeader.addAll({
'Authorization': 'Bearer ' + token,
});
}
if (header != null) {
finalHeader.addAll(header);
}
var request = http.MultipartRequest(
"POST",
Uri.parse(url),
);
request.headers.addAll(finalHeader);
return request;
}
Future uploadProfileImage(File image) async {
var result = {
'status': true,
'msg': 'Success',
'data': {},
};
var request = await httpPostWithFile(
url: Api.CHANGE_DOCTOR_PROFILE_IMAGE,
);
request.files.add(http.MultipartFile(
'image',
image.readAsBytes().asStream(),
image.lengthSync(),
filename: image.path.split('/').last,
));
await request.send().then((streamResponse) async {
await http.Response.fromStream(streamResponse).then((response) {
var parsedData = jsonDecode(response.body);
print('parsed respoinse for prfile image change');
print(parsedData);
if (response.statusCode == 200) {
result['data'] = parsedData['data'];
} else {
result['status'] = false;
result['msg'] =
parsedData['msg'] ?? 'Failed to upload profile image!';
}
});
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment