Re: [whatwg/fetch] FetchObserver (for a single fetch) (#607)

it's already possible to somewhat get a download progress indicator yourself without any new spec changes. but it's not as fancy/ergonomic as if it would be directly implemented to fetch itself 

1. get the response (you have now uploaded everything)
2. read the `Content-Length` response header to figure out how large the response is
3. get the `response.body` and `pipeThrough` a transform stream that count bytes that you receive. now you know how much you have downloaded
4. (optionally) you might want to `pipe` it to an other dedicated stream handler like the [TextDecoderStream](https://www.chromestatus.com/feature/4881011259211776) to get a strings back or a custom blob builder or anything, here is an example of just piping it to a new reusable `Response` object so that you can use it as you normally would have

```js
let downloaded = 0
let res = await fetch('./')
console.log('done uploading')
const total = res.headers.get('content-length') // might be null also

// An identity stream (no transformation done) 
const ts = new TransformStream({
    transform (chunk, ctrl) {
        downloaded += chunk.byteLength
        console.log(downloaded) // out of `total`
        ctrl.enqueue(chunk)
    }
})

// create a new Response object /w a new ReadableStream from the transformer
res = new Response(res.body.pipeThrough(ts), res)

// use response as you would normally use
res.text().then(console.log)
```

as for the upload progress it ain't possible yet as Request don't support ReadableStreams yet afaik

if you would like to get a wider browser support then you have to use `getReadable` and do more manually reads as pipes are not well supported in browsers other then Blink (?)

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/607#issuecomment-564461907

Received on Wednesday, 11 December 2019 09:46:12 UTC