dart - Flutter - How to download a file from server using binary stream
问题描述
I need to be able to download and display an image from a private server. The request that I send needs to include a header with content-type and a body with sessionToken and userId. The server responds with a binary stream with the Content-type application/octet-stream.
This is the code I have right now:
Future<Null> _downloadFile(String url, String userId, sessionToken) async {
Map map = {'token': sessionToken, 'UserId': userId};
try {
var request = await httpClient.getUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
await _image.writeAsBytes(bytes);
userImage(_image);
}
catch (value){
print(value);
}
}
When I try to read the response I get this error: HttpException: Content size exceeds specified contentLength. 72 bytes written while expected 0.
I've tried to google this endlessly on how to download a file from a server using a stream, but I can't find anything. What I need is something similar to the bitmap class in .NET that can take in a stream and turn it into an image.
Can anybody help me? It would be greatly appreciated.
解决方案
我能够用这段代码成功地做到这一点:
void getImage(String url, String userId, sessionToken) async{
var uri = Uri.parse(url);
Map body = {'Session': sessionToken, 'UserId': userId};
try {
final response = await http.post(uri,
headers: {"Content-Type": "application/json"},
body: utf8.encode(json.encode(body)));
if (response.contentLength == 0){
return;
}
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
File file = new File('$tempPath/$userId.png');
await file.writeAsBytes(response.bodyBytes);
displayImage(file);
}
catch (value) {
print(value);
}
}
谢谢您的帮助 :)
推荐阅读
- scala - Spark Dataframe 在另存为文本文件时附加了方括号
- docker - 使用预编译文件创建 Docker 映像
- c# - 如何通过表示[i,j]的单个变量访问多维数组的元素?
- swift - Xcode 11.5 的 IOS Chart 编译器警告
- python - 从极坐标到笛卡尔坐标的伪彩色图上的流图
- c - 函数内部声明的指针的内存位置
- r - 在使用 R 的 kafka 主题消费流期间,是否有任何 sparklyr 参数可以返回额外的日志信息?
- python - 如何让 Django 扫描所有目录,包括不在静态文件目录中的目录以搜索媒体文件
- html - 无法将其中一个标签向右对齐
- mysql - 在表格字段中插入附加文本