如何将图像文件传递到Http请求(POST)的正文?



I Took a variable in my StateFile? image;

然后从我的设备访问图像

void filePicker() async {
final File? selectedImage =await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
});
}

然后尝试传递image file以及其他HTTP主体参数。如果我没有传递图像文件,那么API不会显示任何错误。但是我需要传递图像文件来获得正确的结果。如我显式抛出异常,所以它抛出异常像Faild to fetchScaffoldMessenger—>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");
}
});
}

}

您应该使用MultiPartpost方法。看看这个

您可以简单地通过以下方式传递图像文件:

//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;
}
}

最后设法解决它使用Multipart..这里是我的完整API函数代码

Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var response = http.MultipartRequest('POST',Uri.parse("http://myApiTestBooking"));
response.fields['VisitDate'] = _selectedDate;
response.fields['EncUserId'] = EncUserId;
response.fields['Description'] = testTextController.text;
response.files.add(new http.MultipartFile.fromBytes(
"UserFile", File(image!.path).readAsBytesSync(),//UserFile is my JSON key,use your own and "image" is the pic im getting from my gallary 
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));

response.send().then((response) async {
if (response.statusCode == 200){
isApiCallProcess = false;
final respBody = await response.stream.bytesToString();// this is how we print body for Multipart request
jsonResponse = json.decode(respBody.toString());
print(respBody);
print("Uploaded!");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Booked"),
backgroundColor: Color(0xFF00b3a4),
));
//  Navigator.push(context,new MaterialPageRoute( builder: (context) =>new MyTestReqDetailsPage(),));
Navigator.push(context,new MaterialPageRoute( builder: (context) =>new Home2(),));
} 
});

}
}