我需要能够从私人服务器下载和显示图像。我发送的请求需要包含带内容类型的标头和带有sessionToken和userId的主体。服务器使用Content-type application / octet-stream以二进制流进行响应。
这是我现在的代码:
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);
}
}
当我尝试读取响应时,我收到此错误:HttpException:内容大小超过指定的contentLength。写入72字节,预期为0。
我试图在如何使用流从服务器下载文件无休止地谷歌,但我找不到任何东西。我需要的是类似于bitmap class in .NET的东西,它可以在流中将其转换为图像。
有谁能够帮我?这将不胜感激。
我能够使用以下代码成功完成此操作:
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);
}
}
谢谢您的帮助 :)