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

Posted

技术标签:

【中文标题】如何将图像文件传递到 Flutter 中的 Http 请求(POST)正文?【英文标题】:How to pass image file to the body of Http request (POST) in Flutter? 【发布时间】:2021-11-11 05:18:24 【问题描述】:

I Take 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;
    );
  

然后尝试传递 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");
    
  );

【问题讨论】:

你打印出base64Encode(image!.readAsBytesSync())看是否已经包含'data:image/jpg;base64,' 没有。但相反,我在我的设备中显示图像。及其显示图像 我也尝试'UserFile':image.toString(),同样的错误...需要将图像转换为base64吗? 【参考方案1】:

你应该使用MultiPart post 方法。看看this。

【讨论】:

【参考方案2】:

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

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

【讨论】:

【参考方案3】:

终于用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(),));

   
);




【讨论】:

以上是关于如何将图像文件传递到 Flutter 中的 Http 请求(POST)正文?的主要内容,如果未能解决你的问题,请参考以下文章

Flutter:如何将值从 streamprovider / listview builder 传递给另一个类

如何将数据从 showmodalbottomsheet 传递到 Flutter 中的上一页

如何将多个图像上传到 Flutter 中的 REST API?

Flutter:如何将 Canvas/CustomPainter 保存到图像文件中?

如何通过共享将文件发送到 Flutter 应用程序?

将文件上传到 S3 时如何传递 ACL 属性以进行颤振放大?