How do I read all binaries from HttpRequest, into Dart?
One way to do this is by setting a callback onDone
for listen()
. The callback is triggered when it is complete. Then just create a list of integers and add to it for each event:
List<int> data = []; request.listen(data.addAll, onDone: () { // `data` has here the entire contents. });
Alternatively, here's a one-liner:
request.reduce((p, e) => p..addAll(e)).then((data) { // `data` has here the entire contents. });
I'll also add Anders Johnsen's excellent advice on using the class BytesBuilder
, which I think you should prefer:
request.fold(new BytesBuilder(), (b, d) => b..add(d)).then((builder) { var data = builder.takeBytes(); });
source to share
We recently added BytesBuilder
to dart:io
. See here for details .
In your case, the code might look like this:
request.fold(new BytesBuilder(), (builder, data) => builder..add(data))
.then((builder) {
var data = builder.takeBytes();
// use data.
});
The cool thing about using it BytesBuilder
is that it is optimized for large chunks of binary data. Please note what I am using takeBytes
to get the internal buffer BytesBuilder
, avoiding the extra copy.
source to share
If you are using dart:html
you can use
HttpRequest.request('/blub.bin', responseType: 'arraybuffer').then((request) {
to get the answer as one array buffer. You can access the buffer via request.response
. But to access the bytes, you need to create a Uint8List
data view :
List<int> bytes = new Uint8List.view(request.response);
source to share