Flutter DIO:使用带有 Dio 包的二进制体上传图像 [英] Flutter DIO: upload image using binary body with Dio package

查看:34
本文介绍了Flutter DIO:使用带有 Dio 包的二进制体上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 http 包,我可以通过将二进制数据放入 post 调用的正文中来将图像发送到服务器,就像此代码的片段一样:

With thwe http package I can send an image to a server by putting te binary data in the body of a post call like in the snippet of this code:

var response = await http.post('My_url', body: File(path).readAsBytesSync(),  headers: {
                    'apikey': 'myAPIKEY',
                    'Content-Type': 'image/*', // set content-length
                  });

我不能用Dio做同样的事情,我不知道如何将二进制数据直接放入body中(就像我可以用postman来做)

I can't do the same thing by using Dio, I don't know how to put directly the binary data in the body (like i can do it with postman)

推荐答案

我也遇到了和你一样的情况.在 DIO 中,您必须通过流发送二进制数据.这是我如何实现它的示例,

I also faced the same you have. In DIO you have to send the binary data through streams. Here is the example how I achieved it,

Uint8List image = File(path).readAsBytesSync();

Options options = Options(
  contentType: lookupMimeType(path),
  headers: {
    'Accept': "*/*",
    'Content-Length': image.length,
    'Connection': 'keep-alive',
    'User-Agent': 'ClinicPlush'
  }
);

Response response = await dio.put(
  url,
  data: Stream.fromIterable(image.map((e) => [e])),
  options: options
);

这篇关于Flutter DIO:使用带有 Dio 包的二进制体上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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