Readable-stream get a blob

Viewed 1358

I am getting a photo from my server. I know that the server send a blob, and that the blob is correct. (server show the bytes).

On client i try to get that blob:

function createFiles(url){

  fetch('https://....jpg', {
  method: 'POST',
  headers: { Accept: 'application/json'}
  })
.then(response =>  response.body)
.then(body => {
  console.log(body);      //** print a streamable object

      const reader = body.getReader();
      return new ReadableStream({
   start(controller) {
     return pump();
     function pump() {
       return reader.read().then(({ done, value }) => {
         // When no more data needs to be consumed, close the stream
         if (done) {
             controller.close();
             return;
         }
         // Enqueue the next data chunk into our target stream
         controller.enqueue(value);
         return pump();
       });
     }
   }
 })
})
.then(stream => new Response(stream))
.then(response => response.blob())
.then(blob => console.log(blob)) // ** print an empty blob size of 2 .
.catch(err => console.error(err));


}

If i print the body right away i see an object which is ReadableStream. (locked:false)

When i print the blob at the end, i get an empty blob which is of type = "" , and size = 2 .

But it suppose to be a photo.

How can i get this blob from the fetch ?

1 Answers

The server responses is a ReadableStream already.

you can try this.

fetch(url)  // and you know it is a file you 
.then(response => response.blob()) // this will give you the blob you wanted
.then(blob => console.log(blob.size))
.catch(err => {console.log(err})

Related