How to pass image file to the body of Http request (POST) in Flutter?
898
You should use MultiPart
post method. Take a look at this.
Author by
Toujo
Updated on January 01, 2023Comments
-
Toujo 5 months
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 likeFaild to fetch
and message inScaffoldMessenger
-->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"); } }); }
}
-
Mohamed Sayed over 1 yeardid you print out
base64Encode(image!.readAsBytesSync())
to see if already contains'data:image/jpg;base64,'
-
Toujo over 1 yearNo . But Instead Im displaying the image in my device. and its showing the image
-
Toujo over 1 yearI also try
'UserFile':image.toString(),
same error... Its necessary to convert the image tobase64
?
-