如何在 Flutter 中将图像文件传递给 Http 请求(POST)的主体? [英] How to pass image file to the body of Http request (POST) in Flutter?

查看:28
本文介绍了如何在 Flutter 中将图像文件传递给 Http 请求(POST)的主体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的状态中取了一个变量文件?图片;

I Took a variable in my State File? image;

然后从我的设备访问图像

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

然后将 图像文件 与其他 http 正文参数一起传递.如果我没有传递图像文件,那么 API 不会显示任何错误.但是我需要传递图像文件才能得到正确的结果.由于我显式抛出异常,所以它的抛出异常如 Faild to fetchScaffoldMessenger 中的消息 -->出了点问题

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");
    }
  });
}

}

推荐答案

你应该使用 MultiPart post 方法.看看 这个.

You should use MultiPart post method. Take a look at this.

这篇关于如何在 Flutter 中将图像文件传递给 Http 请求(POST)的主体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆