如何将HTTP响应的流(图像)转换为文件?

时间:2019-05-04 05:39:32

标签: dart flutter

我想向服务器发送2张图像,并接收图像流作为响应。发送操作正确,但问题是响应。如何将响应流转换为文件?我试图同时使用'writeasString'和'openWrite',但这是行不通的。

这是我的代码。

var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var stream2 = new http.ByteStream(DelegatingStream.typed(extractionImage.openRead()));

var length = await imageFile.length();
var length2 = await extractionImage.length();

var uri = Uri.parse("http://127.0.0.1:8000/style_transfer/form/");       //add
var request = new http.MultipartRequest("POST", uri);

var multipartFile1 = new http.MultipartFile('content_image', stream, length,
    filename: basename(imageFile.path)
);
var multipartFile2 = new http.MultipartFile('style_image', stream2, length2,
  filename: basename(extractionImage.path),
);

request.fields['id'] = '${widget._imagemodel.id}';
request.files.add(multipartFile1);
request.files.add(multipartFile2);

var response = await request.send();
print(response.statusCode);

var responsebody1 = await response.stream.transform(utf8.decoder);

setState(() {
  var sink = _transferedImage.openWrite();
  sink.write(response.stream.transform(utf8.decoder));
  sink.close();
});

我收到此错误消息。

Unhandled Exception: NoSuchMethodError: The method 'openWrite' was called on null.```

1 个答案:

答案 0 :(得分:0)

替换:

var responsebody1 = await response.stream.transform(utf8.decoder);

setState(() {
  var sink = _transferedImage.openWrite();
  sink.write(response.stream.transform(utf8.decoder));
  sink.close();
});

具有:

_transferedImage = File('someFile'); // must assign a File to _transferedImage
IOSink sink = _transferedImage.openWrite();
await sink.addStream(response.stream); // this requires await as addStream is async
await sink.close(); // so does this
setState(() {}); // now it's ok to set state - the returned file is created and closed