我需要能够从私人服务器下载和显示图像。我发送的请求需要包含一个带有 content-type 的标头和一个带有 sessionToken 和 userId 的正文。服务器使用内容类型应用程序/八位字节流的二进制流进行响应。
这是我现在拥有的代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试读取响应时,出现此错误:HttpException:内容大小超出指定的内容长度。已写入 72 个字节,而预期为 0。
我试图无休止地在谷歌上搜索如何使用流从服务器下载文件,但我找不到任何东西。我需要的是类似于.NET中的位图类的东西,它可以接收流并将其转换为图像。
有谁能够帮助我?这将不胜感激。
ann*_*fey 10
我能够使用以下代码成功地做到这一点:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助 :)
| 归档时间: |
|
| 查看次数: |
6868 次 |
| 最近记录: |