-
-
Notifications
You must be signed in to change notification settings - Fork 416
/
saving-a-blob.html
51 lines (45 loc) · 1.79 KB
/
saving-a-blob.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="color-scheme" content="dark light">
<title>Saving a Blob</title>
</head>
<body>
<button id="$start">Start</button>
<script src="https://cdn.jsdelivr.net/npm/web-streams-polyfill@2.0.2/dist/ponyfill.min.js"></script>
<!-- includes blob.stream() polyfill -->
<script src="https://cdn.jsdelivr.net/gh/eligrey/Blob.js/Blob.js"></script>
<script src="../StreamSaver.js"></script>
<script>
// Saving a blob is as simple as the fetch example, you just get the
// readableStream from the blob by calling blob.stream() to get a
// readableStream and then pipe it
$start.onclick = () => {
const blob = new Blob(['StreamSaver is awesome'])
const fileStream = streamSaver.createWriteStream('sample.txt', {
size: blob.size // Makes the percentage visiable in the download
})
// One quick alternetive way if you don't want the hole blob.js thing:
// const readableStream = new Response(
// Blob || String || ArrayBuffer || ArrayBufferView
// ).body
const readableStream = blob.stream()
// more optimized pipe version
// (Safari may have pipeTo but it's useless without the WritableStream)
if (window.WritableStream && readableStream.pipeTo) {
return readableStream.pipeTo(fileStream)
.then(() => console.log('done writing'))
}
// Write (pipe) manually
window.writer = fileStream.getWriter()
const reader = readableStream.getReader()
const pump = () => reader.read()
.then(res => res.done
? writer.close()
: writer.write(res.value).then(pump))
pump()
}
</script>
</body>
</html>