Skip to content

Commit b991b9e

Browse files
committed
Add an example with Blob target.
1 parent b306c28 commit b991b9e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

readme.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,40 @@ const options = {
6767
await fetch("https://httpbin.org/post", options)
6868
```
6969

70+
3. Because the Encoder is async iterable, you can use it with different targets. Let's say you want to put FormData content into `Blob`, for that you can write a function like this:
71+
72+
```js
73+
import {FormData} from "formdata-polyfill/esm-min.js"
74+
import {blobFrom} from "fetch-blob/from.js"
75+
import {Encoder} from "form-data-encoder"
76+
import {Blob} from "fetch-blob" // For this example I will use v3 of this package
77+
78+
import fetch from "node-fetch"
79+
80+
async function toBlob(form) {
81+
const encoder = new Encoder(form)
82+
const chunks = []
83+
84+
for await (const chunk of encoder) {
85+
chunks.push(chunk)
86+
}
87+
88+
return new Blob(chunks, {type: encoder.contentType})
89+
}
90+
91+
const fd = new FormData()
92+
93+
fd.set("name", "John Doe")
94+
fd.set("avatar", await blobFrom("path/to/an/avatar.png"))
95+
96+
const options = {
97+
method: "post",
98+
body: await toBlob(fd)
99+
}
100+
101+
await fetch("https://httpbin.org/post", options)
102+
```
103+
70104
# Installation
71105

72106
You can install this package using npm:

0 commit comments

Comments
 (0)