gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:03:30 29 4
gpt4 key购买 nike

我想向服务器发送 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.```

最佳答案

替换:

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

关于dart - 如何将 HTTP 响应流(图像)转换为文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55979814/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com