I Took a variable in my State File? image;
Then Accesing image from my device
void filePicker() async {
final File? selectedImage =await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
});
}
Then tyring to pass the image file
along with other http body parameters. If I didn't pass the image file, then the API didn't show any error. But I need to pass the image file to get the correct result.
As I Explicitly throw Exception, so its throwing exception like Faild to fetch
and message in ScaffoldMessenger
--> Somthing went wrong
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var postUri = Uri.parse("http://medbo.digitalicon.in/api/medboapi/SaveCustomTestBooking");
var request = http.MultipartRequest('POST', postUri);
request.fields['VisitDate'] = _selectedDate;
request.fields['EncUserId'] = EncUserId;
request.files.add(new http.MultipartFile.fromBytes('image',await File.fromUri(Uri.parse(image!.path)).readAsBytes(),contentType: new MediaType('image', 'jpeg')));
request.send().then((response) {
if (response.statusCode == 200) {
print("Uploaded!");
Navigator.push(context,MaterialPageRoute(builder: (context) => DieticianAfterDateSelectPage(rresponse:DieticianEncBookingIdModel.fromJson(jsonResponse),)));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Somthing went wrong")));
throw Exception("Faild to fetch");
}
});
}
}
CodePudding user response:
You should use MultiPart
post method. Take a look at this.
CodePudding user response:
You can pass image file simply in this way:
//header
var headers = {
'content-type': 'multipart/form-data',
'Accept': 'application/json',
};
//setup request
var request = http.MultipartRequest(
"POST", Uri.parse("your api url"));
//add files to reqest body
request.files.add(await http.MultipartFile.fromPath(
'your feild name',
pickedFile.path,
));
//add header
request.headers.addAll(headers);
//send request and return response
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
}