| 9 |
lars |
1 |
FileSaver.js
|
|
|
2 |
============
|
|
|
3 |
|
|
|
4 |
FileSaver.js implements the W3C `saveAs()` [FileSaver][1] interface in browsers that do
|
|
|
5 |
not natively support it. There is a [FileSaver.js demo][2] that demonstrates saving
|
|
|
6 |
various media types.
|
|
|
7 |
|
|
|
8 |
FileSaver.js is the solution to saving files on the client side, and is perfect for
|
|
|
9 |
webapps that need to generate files or for saving sensitive information that shouldn't be
|
|
|
10 |
sent to an external server.
|
|
|
11 |
|
|
|
12 |
Supported Browsers
|
|
|
13 |
------------------
|
|
|
14 |
|
|
|
15 |
* Internet Explorer 10+
|
|
|
16 |
* Firefox 4+
|
|
|
17 |
* Google Chrome
|
|
|
18 |
* Opera 11+
|
|
|
19 |
* Safari 5+
|
|
|
20 |
|
|
|
21 |
Unlisted versions of browsers (e.g. Firefox 3.6) will probably work too; I just haven't
|
|
|
22 |
tested them.
|
|
|
23 |
|
|
|
24 |
Syntax
|
|
|
25 |
------
|
|
|
26 |
|
|
|
27 |
FileSaver saveAs(in Blob data, in DOMString filename)
|
|
|
28 |
|
|
|
29 |
Examples
|
|
|
30 |
--------
|
|
|
31 |
|
|
|
32 |
### Saving text
|
|
|
33 |
|
|
|
34 |
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
|
|
|
35 |
saveAs(blob, "hello world.txt");
|
|
|
36 |
|
|
|
37 |
The standard W3C File API [`Blob`][3] interface is not available in all browsers.
|
|
|
38 |
[Blob.js][4] is a cross-browser `BlobBuilder` implementation that solves this.
|
|
|
39 |
|
|
|
40 |
### Saving a canvas
|
|
|
41 |
|
|
|
42 |
var canvas = document.getElementById("my-canvas"), ctx = canvas.getContext("2d");
|
|
|
43 |
// draw to canvas...
|
|
|
44 |
canvas.toBlob(function(blob) {
|
|
|
45 |
saveAs(blob, "pretty image.png");
|
|
|
46 |
});
|
|
|
47 |
|
|
|
48 |
Note: The standard HTML5 `canvas.toBlob()` method is not available in all browsers.
|
|
|
49 |
[canvas-toBlob.js][5] is a cross-browser `canvas.toBlob()` implementation that solves
|
|
|
50 |
this.
|
|
|
51 |
|
|
|
52 |
### Aborting a save
|
|
|
53 |
|
|
|
54 |
var filesaver = saveAs(blob, "whatever");
|
|
|
55 |
cancel_button.addEventListener("click", function() {
|
|
|
56 |
if (filesaver.abort) {
|
|
|
57 |
filesaver.abort();
|
|
|
58 |
}
|
|
|
59 |
}, false);
|
|
|
60 |
|
|
|
61 |
This isn't that useful unless you're saving very large files (e.g. generated video).
|
|
|
62 |
|
|
|
63 |

|
|
|
64 |
|
|
|
65 |
[1]: http://www.w3.org/TR/file-writer-api/#the-filesaver-interface
|
|
|
66 |
[2]: http://oftn.org/projects/FileSaver.js/demo/
|
|
|
67 |
[3]: https://developer.mozilla.org/en-US/docs/DOM/Blob
|
|
|
68 |
[4]: https://github.com/eligrey/Blob.js
|
|
|
69 |
[5]: https://github.com/eligrey/canvas-toBlob.js
|