From 5b94c4440714de15643eb30fc0fe1e1c504c6141 Mon Sep 17 00:00:00 2001 From: Eli Grey Date: Thu, 14 Jul 2011 23:28:11 -0400 Subject: [PATCH] Initial commit --- FileSaver.js | 168 ++++++++++++++++++++++++++++++++++++++ FileSaver.min.js | 2 + LICENSE.md | 30 +++++++ README.md | 75 +++++++++++++++++ demo/demo.css | 55 +++++++++++++ demo/demo.js | 205 +++++++++++++++++++++++++++++++++++++++++++++++ demo/demo.min.js | 2 + demo/index.xhtml | 68 ++++++++++++++++ 8 files changed, 605 insertions(+) create mode 100644 FileSaver.js create mode 100644 FileSaver.min.js create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 demo/demo.css create mode 100644 demo/demo.js create mode 100644 demo/demo.min.js create mode 100644 demo/index.xhtml diff --git a/FileSaver.js b/FileSaver.js new file mode 100644 index 0000000..a8aa8a9 --- /dev/null +++ b/FileSaver.js @@ -0,0 +1,168 @@ +/* FileSaver.js + * A saveAs() FileSaver implementation. + * 2011-07-13 + * + * By Eli Grey, http://eligrey.com + * License: X11/MIT + * See LICENSE.md + */ + +/*global self, open, setTimeout */ +/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true, + plusplus: true */ + +/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ + +var saveAs = saveAs || (function(view) { + "use strict"; + var + URL = view.URL || view.webkitURL || view + , webkit_req_fs = view.webkitRequestFileSystem + , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem + , throw_outside = function (ex) { + (view.setImmediate || setTimeout)(function() { + throw ex; + }, 0); + } + , force_saveable_type = "application/octet-stream" + , fs_min_size = 0 + , deletion_queue = [] + , process_deletion_queue = function() { + var i = deletion_queue.length; + while (i--) { + var file = deletion_queue[i]; + if (typeof file === "string") { // file is an object URL + URL.revokeObjectURL(file); + } else { // file is a File + file.remove(); + } + } + deletion_queue.length = 0; // clear queue + } + , dispatch = function(filesaver, event_types, event) { + event_types = [].concat(event_types); + var i = event_types.length; + while (i--) { + var listener = filesaver["on" + event_types[i]]; + if (typeof listener === "function") { + try { + listener.call(filesaver, event || filesaver); + } catch (ex) { + throw_outside(ex); + } + } + } + } + , FileSaver = function(blob, name) { + var + filesaver = this + , type = blob.type + // on any filesys errors revert to saving with object URLs + , fs_error = function() { + var object_url = URL.createObjectURL(blob); + target_view.location.href = object_url; + deletion_queue.push(object_url); + filesaver.readyState = 2; // DONE + dispatch(filesaver, "writestart progress write writeend".split(" ")); + } + , abortable = function(func) { + return function() { + if (filesaver.readyState !== 2) { // DONE + return func.apply(this, arguments); + } + }; + } + , target_view + ; + filesaver.readyState = filesaver.INIT; + if (!name) { + name = "download"; + } + // Object and web filesystem URLs have a problem saving in WebKit when viewed + // in a tab, so I force object URLs to save with application/octet-stream + // and web filesystem URLs to save by appending .download to the filename. + if (blob.webkitSlice && type !== force_saveable_type) { + blob = blob.webkitSlice(0, blob.size, force_saveable_type); + } + if (webkit_req_fs && name !== "download") { + name += ".download"; + } + if (type === force_saveable_type || webkit_req_fs) { + target_view = self; + } else { + target_view = open(); + } + if (!req_fs) { + fs_error(); + return; + } + fs_min_size += blob.size; + req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) { + fs.root.getDirectory("saved", {create:true, exclusive: false}, abortable(function(dir) { + var save = function() { + dir.getFile(name, {create:true, exclusive: false}, abortable(function(file) { + file.createWriter(abortable(function(writer) { + writer.onwriteend = function(event) { + target_view.location.href = file.toURL(); + deletion_queue.push(file); + filesaver.readyState = filesaver.DONE; + dispatch(filesaver, "writeend", event); + }; + writer.onerror = function() { + var error = writer.error; + if (error.code !== error.ABORT_ERR) { + fs_error(); + } + }; + "writestart progress write abort".split(" ").forEach(function(event) { + writer["on" + event] = filesaver["on" + event]; + }); + writer.write(blob); + filesaver.abort = function() { + writer.abort(); + filesaver.readyState = filesaver.DONE; + }; + filesaver.readyState = filesaver.WRITING; + }), fs_error); + }), fs_error); + }; + dir.getFile(name, {create: false}, abortable(function(file) { + // delete file if it already exists + file.remove(); + save(); + }), abortable(function(ex) { + if (ex.code === ex.NOT_FOUND_ERR) { + save(); + } else { + fs_error(); + } + })); + }), fs_error); + }), fs_error); + } + , FS_proto = FileSaver.prototype + , saveAs = function(blob, name) { + return new FileSaver(blob, name); + } + ; + FS_proto.abort = function() { + var filesaver = this; + filesaver.readyState = filesaver.DONE; + dispatch(filesaver, "abort"); + }; + FS_proto.readyState = FS_proto.INIT = 0; + FS_proto.WRITING = 1; + FS_proto.DONE = 2; + + FS_proto.error = + FS_proto.onwritestart = + FS_proto.onprogress = + FS_proto.onwrite = + FS_proto.onabort = + FS_proto.onerror = + FS_proto.onwriteend = + null; + + view.addEventListener("unload", process_deletion_queue, false); + return saveAs; +}(self)); \ No newline at end of file diff --git a/FileSaver.min.js b/FileSaver.min.js new file mode 100644 index 0000000..4c94f6a --- /dev/null +++ b/FileSaver.min.js @@ -0,0 +1,2 @@ +/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ +var saveAs=saveAs||(function(l){"use strict";var k=l.URL||l.webkitURL||l,f=l.webkitRequestFileSystem,m=l.requestFileSystem||f||l.mozRequestFileSystem,c=function(n){(l.setImmediate||setTimeout)(function(){throw n},0)},j="application/octet-stream",h=0,g=[],e=function(){var o=g.length;while(o--){var n=g[o];if(typeof n==="string"){k.revokeObjectURL(n)}else{n.remove()}}g.length=0},i=function(o,n,r){n=[].concat(n);var q=n.length;while(q--){var s=o["on"+n[q]];if(typeof s==="function"){try{s.call(o,r||o)}catch(p){c(p)}}}},b=function(o,q){var n=this,r=o.type,t=function(){var u=k.createObjectURL(o);p.location.href=u;g.push(u);n.readyState=2;i(n,"writestart progress write writeend".split(" "))},s=function(u){return function(){if(n.readyState!==2){return u.apply(this,arguments)}}},p;n.readyState=n.INIT;if(!q){q="download"}if(o.webkitSlice&&r!==j){o=o.webkitSlice(0,o.size,j)}if(f&&q!=="download"){q+=".download"}if(r===j||f){p=self}else{p=open()}if(!m){t();return}h+=o.size;m(l.TEMPORARY,h,s(function(u){u.root.getDirectory("saved",{create:true,exclusive:false},s(function(v){var w=function(){v.getFile(q,{create:true,exclusive:false},s(function(x){x.createWriter(s(function(y){y.onwriteend=function(z){p.location.href=x.toURL();g.push(x);n.readyState=n.DONE;i(n,"writeend",z)};y.onerror=function(){var z=y.error;if(z.code!==z.ABORT_ERR){t()}};"writestart progress write abort".split(" ").forEach(function(z){y["on"+z]=n["on"+z]});y.write(o);n.abort=function(){y.abort();n.readyState=n.DONE};n.readyState=n.WRITING}),t)}),t)};v.getFile(q,{create:false},s(function(x){x.remove();w()}),s(function(x){if(x.code===x.NOT_FOUND_ERR){w()}else{t()}}))}),t)}),t)},a=b.prototype,d=function(n,o){return new b(n,o)};a.abort=function(){var n=this;n.readyState=n.DONE;i(n,"abort")};a.readyState=a.INIT=0;a.WRITING=1;a.DONE=2;a.error=a.onwritestart=a.onprogress=a.onwrite=a.onabort=a.onerror=a.onwriteend=null;l.addEventListener("unload",e,false);return d}(self)); \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..7eb56b9 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,30 @@ +This software is licensed under the MIT/X11 license. + +MIT/X11 license +--------------- + +Copyright © 2011 [Eli Grey][1]. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + + + [1]: http://eligrey.com \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..2169ba2 --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +FileSaver.js +============ + +FileSaver.js implements the W3C `saveAs()` [FileSaver][1] interface in browsers that do +not natively support it. There is a [FileSaver.js demo][2] that demonstrates saving +various media types. + +FileSaver.js is the solution to saving files on the client side, and is perfect for +webapps that need to generate files or for saving sensitive information that shouldn't be +sent to an external server. + +Supported Browsers +------------------ + +* Firefox 4+ +* †Google Chrome +* Opera 11+ +* Safari 5+ + +Unlisted versions of browsers (e.g. Firefox 3.6) will probably work too; I just haven't +tested them. + +† Google Chrome 14+ supports saving with filenames + +Syntax +------ + + FileSaver saveAs(in Blob data, in DOMString filename); + +Examples +-------- + +### Saving text + + var bb = new BlobBuilder; + bb.append("Hello, world!"); + saveAs(bb.getBlob("text/plain;charset=utf-8"), "hello world.txt"); + +The standard W3C File API [`BlobBuilder`][3] interface is not available in all browsers. +[BlobBuilder.js][4] is a cross-browser `BlobBuilder` implementation that solves this. + +### Saving a canvas + + var canvas = document.getElementById("my-canvas"), ctx = canvas.getContext("2d"); + // draw to canvas... + canvas.toBlob(function(blob) { + saveAs(blob, "pretty image.png"); + }); + +Note: The standard HTML5 `canvas.toBlob()` method is not available in all browsers. +[canvas-toBlob.js][5] is a cross-browser `canvas.toBlob()` implementation that solves +this. + +### Doing something after a file is saved + + var filesaver = saveAs(blob, "secret stuff that you won't send to a server.truecrypt"); + filesaver.onwriteend = function() { + // file saved, do something here + }; + +### Aborting a save + + var filesaver = saveAs(blob, "whatever"); + cancel_button.addEventListener("click", function() { + filesaver.abort(); + }, false); + +This isn't that useful unless you're saving very large files (e.g. generated video). + + + [1]: http://www.w3.org/TR/file-writer-api/#the-filesaver-interface + [2]: http://oftn.org/projects/FileSaver.js/demo/ + [3]: http://www.w3.org/TR/file-writer-api/#the-blobbuilder-interface + [4]: https://github.com/eligrey/BlobBuilder.js + [5]: https://github.com/eligrey/canvas-toBlob.js \ No newline at end of file diff --git a/demo/demo.css b/demo/demo.css new file mode 100644 index 0000000..7b4d837 --- /dev/null +++ b/demo/demo.css @@ -0,0 +1,55 @@ +html { + background-color: #DDD; +} +body { + width: 900px; + margin: 0 auto; + font-family: Verdana, Helvetica, Arial, sans-serif; + box-shadow: 0 0 5px #000; + box-shadow: 0 0 10px 2px rgba(0, 0, 0, .5); + padding: 7px 25px; + background-color: #FFF; +} +h1, h2, h3, h4, h5, h6 { + font-family: Georgia, "Times New Roman", serif; +} +h2, form { + text-align: center; +} +form { + margin-top: 5px; +} +.input { + width: 500px; + height: 300px; + margin: 0 auto; + display: block; +} +section { + margin-top: 40px; +} +dt { + font-weight: bold; + font-size: larger; +} +#canvas { + cursor: crosshair; +} +#canvas, #html { + border: 1px solid black; +} +.filename { + text-align: right; +} +#html { + box-sizing: border-box; + ms-box-sizing: border-box; + webkit-box-sizing: border-box; + moz-box-sizing: border-box; + overflow: auto; + padding: 1em; +} +dt:target { + background-color: Highlight; + color: HighlightText; +} \ No newline at end of file diff --git a/demo/demo.js b/demo/demo.js new file mode 100644 index 0000000..338d3b9 --- /dev/null +++ b/demo/demo.js @@ -0,0 +1,205 @@ +/* FileSaver.js demo script + * 2011-07-14 + * + * By Eli Grey, http://eligrey.com + * License: X11/MIT + * See LICENSE.md + */ + +/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */ + +(function(view) { +"use strict"; +// The canvas drawing portion of the demo is based off the demo at +// http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/ +var + document = view.document + , $ = function(id) { + return document.getElementById(id); + } + , session = view.sessionStorage + , BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder + + , canvas = $("canvas") + , canvas_options_form = $("canvas-options") + , canvas_filename = $("canvas-filename") + , canvas_clear_button = $("canvas-clear") + + , text = $("text") + , text_options_form = $("text-options") + , text_filename = $("text-filename") + + , html = $("html") + , html_options_form = $("html-options") + , html_filename = $("html-filename") + + , ctx = canvas.getContext("2d") + , drawing = false + , x_points = session.x_points || [] + , y_points = session.y_points || [] + , drag_points = session.drag_points || [] + , add_point = function(x, y, dragging) { + x_points.push(x); + y_points.push(y); + drag_points.push(dragging); + } + , draw = function(){ + canvas.width = canvas.width; + ctx.lineWidth = 6; + ctx.lineJoin = "round"; + ctx.strokeStyle = "#000000"; + var + i = 0 + , len = x_points.length + ; + for(; i < len; i++) { + ctx.beginPath(); + if (i && drag_points[i]) { + ctx.moveTo(x_points[i-1], y_points[i-1]); + } else { + ctx.moveTo(x_points[i]-1, y_points[i]); + } + ctx.lineTo(x_points[i], y_points[i]); + ctx.closePath(); + ctx.stroke(); + } + } + , stop_drawing = function() { + drawing = false; + } + + // Title guesser and document creator available at https://gist.github.com/1059648 + , guess_title = function(doc) { + var + h = "h6 h5 h4 h3 h2 h1".split(" ") + , i = h.length + , headers + , header_text + ; + while (i--) { + headers = doc.getElementsByTagName(h[i]); + for (var j = 0, len = headers.length; j < len; j++) { + header_text = headers[j].textContent.trim(); + if (header_text) { + return header_text; + } + } + } + } + , doc_impl = document.implementation + , create_html_doc = function(html) { + var + dt = doc_impl.createDocumentType('html', null, null) + , doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt) + , doc_el = doc.documentElement + , head = doc_el.appendChild(doc.createElement("head")) + , charset_meta = head.appendChild(doc.createElement("meta")) + , title = head.appendChild(doc.createElement("title")) + , body = doc_el.appendChild(doc.createElement("body")) + , i = 0 + , len = html.childNodes.length + ; + charset_meta.setAttribute("charset", html.ownerDocument.characterSet); + for (; i < len; i++) { + body.appendChild(doc.importNode(html.childNodes.item(i), true)); + } + var title_text = guess_title(doc); + if (title_text) { + title.appendChild(doc.createTextNode(title_text)); + } + return doc; + } +; +canvas.width = 500; +canvas.height = 300; + + if (typeof x_points === "string") { + x_points = JSON.parse(x_points); +} if (typeof y_points === "string") { + y_points = JSON.parse(y_points); +} if (typeof drag_points === "string") { + drag_points = JSON.parse(drag_points); +} if (session.canvas_filename) { + canvas_filename.value = session.canvas_filename; +} if (session.text) { + text.value = session.text; +} if (session.text_filename) { + text_filename.value = session.text_filename; +} if (session.html) { + html.innerHTML = session.html; +} if (session.html_filename) { + html_filename.value = session.html_filename; +} + +drawing = true; +draw(); +drawing = false; + +canvas_clear_button.addEventListener("click", function() { + canvas.width = canvas.width; + x_points.length = + y_points.length = + drag_points.length = + 0; +}, false); +canvas.addEventListener("mousedown", function(event) { + drawing = true; + add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false); + draw(); +}, false); +canvas.addEventListener("mousemove", function(event) { + if (drawing) { + add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true); + draw(); + } +}, false); +canvas.addEventListener("mouseup", stop_drawing, false); +canvas.addEventListener("mouseout", stop_drawing, false); + +canvas_options_form.addEventListener("submit", function(event) { + event.preventDefault(); + canvas.toBlob(function(blob) { + saveAs( + blob + , (canvas_filename.value || canvas_filename.placeholder) + ".png" + ); + }, "image/png"); +}, false); + +text_options_form.addEventListener("submit", function(event) { + event.preventDefault(); + var bb = new BlobBuilder; + bb.append(text.value || text.placeholder); + saveAs( + bb.getBlob("text/plain;charset=" + document.characterSet) + , (text_filename.value || text_filename.placeholder) + ".txt" + ); +}, false); + +html_options_form.addEventListener("submit", function(event) { + event.preventDefault(); + var + bb = new BlobBuilder + , xml_serializer = new XMLSerializer + , doc = create_html_doc(html) + ; + bb.append(xml_serializer.serializeToString(doc)); + saveAs( + bb.getBlob("application/xhtml+xml;charset=" + document.characterSet) + , (html_filename.value || html_filename.placeholder) + ".xhtml" + ); +}, false); + +view.addEventListener("unload", function() { + session.x_points = JSON.stringify(x_points); + session.y_points = JSON.stringify(y_points); + session.drag_points = JSON.stringify(drag_points); + session.canvas_filename = canvas_filename.value; + + session.text = text.value; + session.text_filename = text_filename.value; + + session.html = html.innerHTML; + session.html_filename = html_filename.value; +}, false); +}(self)); \ No newline at end of file diff --git a/demo/demo.min.js b/demo/demo.min.js new file mode 100644 index 0000000..e70def7 --- /dev/null +++ b/demo/demo.min.js @@ -0,0 +1,2 @@ +/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */ +(function(o){"use strict";var t=o.document,g=function(A){return t.getElementById(A)},b=o.sessionStorage,j=o.BlobBuilder||o.WebKitBlobBuilder||o.MozBlobBuilder,f=g("canvas"),s=g("canvas-options"),y=g("canvas-filename"),q=g("canvas-clear"),r=g("text"),u=g("text-options"),h=g("text-filename"),n=g("html"),e=g("html-options"),i=g("html-filename"),v=f.getContext("2d"),z=false,a=b.x_points||[],p=b.y_points||[],d=b.drag_points||[],k=function(A,C,B){a.push(A);p.push(C);d.push(B)},m=function(){f.width=f.width;v.lineWidth=6;v.lineJoin="round";v.strokeStyle="#000000";var B=0,A=a.length;for(;B + + + +FileSaver.js Demo + + + +

FileSaver.js Demo

+

+The following examples demonstrate how it is possible to generate and save any type of data right in the browser using the W3C saveAs() FileSaver interface, without contacting any servers. +

+
+

Saving an image

+ +
+ + + +
+
+
+

Saving text

+