【问题标题】:How to pass image file in Multi-Part Requests as http body parameter(POST)如何将多部分请求中的图像文件作为 http 正文参数(POST)传递
【发布时间】: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");

   }
   }


   );}

}

【问题讨论】:

    标签: json flutter api dart


    【解决方案1】:

    这是使用 Multipart Request 在 Http body 参数中使用图像的代码示例。

      request.files.add(new http.MultipartFile.fromBytes(
            "thumbnail", File(thumbnailImage.path).readAsBytesSync(),
            filename:"Image.jpg",
            contentType: MediaType('image', 'jpg')));
    

    这里的“缩略图”是 json 关键字名称。用你自己的。谢谢

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2023-04-08
      • 1970-01-01
      • 2016-11-14
      • 2011-05-06
      • 2021-11-08
      • 2016-01-25
      • 1970-01-01
      • 2020-01-24
      相关资源
      最近更新 更多