有时我们需要在浏览器上生成文件并保存到本地,这个借助 FileSaver.js 就可以很方便地实现。
FileSaver.js使用说明
实现浏览器端生成并保存文件的 JavaScript 库 FileSaver.js 使用说明:
一、引入 JavaScript 文件:
1 |
< script src = "path/FileSaver.js" /> |
二、例子:
保存成文本文件
1 2 |
var blob = new Blob([ "Hello, world!" ], {type: "text/plain;charset=utf-8" }); saveAs(blob, "hello world.txt" ); |
保存成图片
1 2 3 |
var canvas = document.getElementById( "my-canvas" ), ctx = canvas.getContext( "2d" ); // draw to canvas...canvas.toBlob(function(blob) { saveAs(blob, "pretty image.png" ); }); |
支持的浏览器:
Browser | Constructs as | Filenames | Max Blob Size | Dependencies |
---|---|---|---|---|
Firefox 20+ | Blob | Yes | 800 MiB | None |
Firefox < 20 | data: URI | No | n/a | Blob.js |
Chrome | Blob | Yes | 500 MiB | None |
Chrome for Android | Blob | Yes | 500 MiB | None |
IE 10+ | Blob | Yes | 600 MiB | None |
Opera 15+ | Blob | Yes | 500 MiB | None |
Opera < 15 | data: URI | No | n/a | Blob.js |
Safari 6.1+* | Blob | No | ? | None |
Safari < 6 | data: URI | No | n/a | Blob.js |
演示页面:FileSaver