I geeting Image from my gallery, Now want to use this image as in Http body parameters using Multipart
Request. I didn't able to figured out what I should pass for Image in Multipart request.
My variable image
contain my gallery image after method call.
final ImagePicker _picker = ImagePicker();
File? image;
var fileContent;
var fileContentBase64;
Showing the image in my App
Padding(
padding: const EdgeInsets.all(18.0),
child: image == null? Text("No file chosen"): Image.file(
File(image!.path),
width: 150,
fit: BoxFit.cover,
),
),
Function to get image from gallery
void filePicker() async {
final File? selectedImage =
await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
fileContent = image!.readAsBytesSync();
fileContentBase64 = base64.encode(fileContent);
});
}
Now in Api Function how should I use it ?
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var postUri = Uri.parse("http://myAPIstomTestBooking");
var request = http.MultipartRequest('POST',postUri);
request.fields['VisitDate'] = '_selectedDate';
request.fields['EncUserId'] = 'EncUserId';
request.files.add(new http.MultipartFile.fromBytes(
"UserFile", File(image!.path).readAsBytesSync(),
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));
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:
Here is code example of using image as in Http body parameters using Multipart Request.
request.files.add(new http.MultipartFile.fromBytes(
"thumbnail", File(thumbnailImage.path).readAsBytesSync(),
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));
here "thumbnail" is json keyword name. use your own. Thanks