简体   繁体   English

可读流得到一个 blob

[英]Readable-stream get a blob

I am getting a photo from my server.我正在从我的服务器获取一张照片。 I know that the server send a blob , and that the blob is correct .我知道服务器发送了一个blob ,并且 blob 是正确的。 (server show the bytes). (服务器显示字节)。

On client i try to get that blob :在客户端上,我尝试获取该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 .如果我立即打印body ,我会看到一个 object ,它是ReadableStream (locked:false) (锁定:假)

When i print the blob at the end, i get an empty blob which is of type = "" , and size = 2 .当我在最后打印blob时,我得到一个type = ""size = 2blob

But it suppose to be a photo.但应该是照片。

How can i get this blob from the fetch ?我怎样才能从fetch中得到这个 blob?

The server responses is a ReadableStream already.服务器响应已经是 ReadableStream。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM