我从抖动的http服务器发送图像文件作为Http响应时遇到问题。当代码看似可行时,该映像将以正确的名称下载到客户端,但已损坏且无法打开。很多时候,客户端会引发异常:Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
已经在多个图像和物理设备上进行了测试。
在局域网上的两个android设备上串联使用此代码,目标IP已为其中一个设备进行了硬编码。 (有关如何通过广播或其他方式获取该IP的建议,将不胜感激:)
服务器:
Future _startWebServer() async {
runZoned(() {
String requestString;
HttpServer.bind(InternetAddress.anyIPv4, 8080).then((server) {
server.transform(HttpBodyHandler()).listen((HttpRequestBody body) async {
requestString = utf8.decode(body.body);
switch (requestString) {
case 'fileName':
{
body.request.response.write(basename(_imageFile.path));
body.request.response.close();
break;
}
case 'file':
{
body.request.response.write(_imageFile.readAsBytesSync());
body.request.response.close();
break;
}
default:
{
body.request.response.write('hello from server!');
body.request.response.close();
}
}
});
});
},
onError: (e, stackTrace) => print('Oh No! $e $stackTrace'));
}
客户端:
File _imageFile;
void _receiveData() async {
String fileName = "FILE1";
HttpClient client = new HttpClient();
await client.getUrl(Uri.parse("http://192.168.1.11:8080"))
.then((HttpClientRequest request) {
request.headers.contentLength = utf8.encode('fileName').length;
request.write('fileName');
return request.close();
})
.then((HttpClientResponse response) {
response.transform(utf8.decoder).listen((contents){
centerText = contents;
fileName = contents;
});
setState(() {});
});
Directory tempDir = await getExternalStorageDirectory();
var fileSave = new File(tempDir.path + '/' + fileName);
var _downloadedData = List<int>();
await client.getUrl(Uri.parse("http://192.168.1.11:8080"))
.then((HttpClientRequest request) {
request.headers.contentLength = utf8.encode('file').length;
request.write('file');
return request.close();
})
.then((HttpClientResponse response) async {
print('Received file');
//------------------Decode error here-----------------
response.listen((d) => _downloadedData.addAll(d),
onDone:(){
fileSave.writeAsBytes(_downloadedData);
});
setState(() {
_imageFile = fileSave;
});
});
client.close();
}
对于问题或整个代码的任何建议,评论和评论,我们将不胜感激。谢谢!
答案 0 :(得分:0)
没有意识到body.request.response.write()
将_imageFile.readAsBytesSync() as List<int>
转换为字符串。通过将body.request.response.write(_imageFile.readAsBytesSync());
更改为body.request.response.add(_imageFile.readAsBytesSync());
.add将List<int>
“添加”到响应正文。