How do I read all binaries from HttpRequest, into Dart?

HttpRequest

in Dart, is Stream<List<int>>

how to get binary content like List<int>

?

I tried:

request.toList().then((data) {
    // but data is a List<List<int>> !!!
});

      

It seems I shouldn't be using toList

. What is the correct method I should be using?

+5


source to share


3 answers


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();
 });

      

+6


source


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.

+7


source


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);

      

+2


source







All Articles