// 通过attach的id属性读取图片,api接口返回图片的二进制数据
getImage(MyAttach attach) async {
Dio dio = Dio();
SharedPreferences sp = await SharedPreferences.getInstance();
dio.options.baseUrl = ServerUrl.base;
dio.options.responseType = ResponseType.STREAM;
Map<String, dynamic> headers = Map();
headers["Authorization"] = sp.getString("token");
dio.options.headers = headers;
try {
String url =
"${ServerUrl.company}/${sp.getString("company_id")}/profile/${attach.id}?type=attach";
print("url:$url");
Response response = await dio.get(url);
HttpClientResponse resp = response.data;
final Uint8List bytes = await consolidateHttpClientResponseBytes(resp);
print("服务器返回:${bytes.length}");
attach.img = Image.memory(bytes);
data.add(attach);
setState(() {});
} catch (e) {
print("网络错误:" + e.toString());
}
}
Future<Uint8List> consolidateHttpClientResponseBytes(
HttpClientResponse response) {
// response.contentLength is not trustworthy when GZIP is involved
// or other cases where an intermediate transformer has been applied
// to the stream.
final Completer<Uint8List> completer = Completer<Uint8List>.sync();
final List<List<int>> chunks = <List<int>>[];
int contentLength = 0;
response.listen((List<int> chunk) {
chunks.add(chunk);
contentLength += chunk.length;
}, onDone: () {
final Uint8List bytes = Uint8List(contentLength);
int offset = 0;
for (List<int> chunk in chunks) {
bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
completer.complete(bytes);
}, onError: completer.completeError, cancelOnError: true);
return completer.future;
}
flutter通过dio读取二进制数据,比如通过api接口读取图片
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 一、需求提出 在一个以flask为框架的项目中,有时需要把上传的图片存入数据库以保障不易丢失。 二、原理 以二进制...