【发布时间】:2021-11-14 18:55:27
【问题描述】:
我从我的图库中获取图像,现在想使用此图像作为 Http 正文参数使用 Multipart 请求。我无法弄清楚我应该为 Multipart 请求中的 Image 传递什么。
我的变量 image 在方法调用后包含我的画廊图像。
final ImagePicker _picker = ImagePicker();
File? image;
var fileContent;
var fileContentBase64;
在我的应用中显示图片
Padding(
padding: const EdgeInsets.all(18.0),
child: image == null? Text("No file chosen"): Image.file(
File(image!.path),
width: 150,
fit: BoxFit.cover,
),
),
从图库中获取图片的功能
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);
});
}
现在在 Api Function 中我应该如何使用它?
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");
}
}
);}
}
【问题讨论】: