FileSaver.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*! FileSaver.js
  2. * A saveAs() FileSaver implementation.
  3. * 2014-01-24
  4. *
  5. * By Eli Grey, http://eligrey.com
  6. * License: X11/MIT
  7. * See LICENSE.md
  8. */
  9. /*global self */
  10. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  11. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  12. var saveAs = saveAs
  13. // IE 10+ (native saveAs)
  14. || (typeof navigator !== "undefined" &&
  15. navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))
  16. // Everyone else
  17. || (function(view) {
  18. "use strict";
  19. // IE <10 is explicitly unsupported
  20. if (typeof navigator !== "undefined" &&
  21. /MSIE [1-9]\./.test(navigator.userAgent)) {
  22. return;
  23. }
  24. var
  25. doc = view.document
  26. // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
  27. , get_URL = function() {
  28. return view.URL || view.webkitURL || view;
  29. }
  30. , URL = view.URL || view.webkitURL || view
  31. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  32. , can_use_save_link = !view.externalHost && "download" in save_link
  33. , click = function(node) {
  34. var event = doc.createEvent("MouseEvents");
  35. event.initMouseEvent(
  36. "click", true, false, view, 0, 0, 0, 0, 0
  37. , false, false, false, false, 0, null
  38. );
  39. node.dispatchEvent(event);
  40. }
  41. , webkit_req_fs = view.webkitRequestFileSystem
  42. , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  43. , throw_outside = function(ex) {
  44. (view.setImmediate || view.setTimeout)(function() {
  45. throw ex;
  46. }, 0);
  47. }
  48. , force_saveable_type = "application/octet-stream"
  49. , fs_min_size = 0
  50. , deletion_queue = []
  51. , process_deletion_queue = function() {
  52. var i = deletion_queue.length;
  53. while (i--) {
  54. var file = deletion_queue[i];
  55. if (typeof file === "string") { // file is an object URL
  56. URL.revokeObjectURL(file);
  57. } else { // file is a File
  58. file.remove();
  59. }
  60. }
  61. deletion_queue.length = 0; // clear queue
  62. }
  63. , dispatch = function(filesaver, event_types, event) {
  64. event_types = [].concat(event_types);
  65. var i = event_types.length;
  66. while (i--) {
  67. var listener = filesaver["on" + event_types[i]];
  68. if (typeof listener === "function") {
  69. try {
  70. listener.call(filesaver, event || filesaver);
  71. } catch (ex) {
  72. throw_outside(ex);
  73. }
  74. }
  75. }
  76. }
  77. , FileSaver = function(blob, name) {
  78. // First try a.download, then web filesystem, then object URLs
  79. var
  80. filesaver = this
  81. , type = blob.type
  82. , blob_changed = false
  83. , object_url
  84. , target_view
  85. , get_object_url = function() {
  86. var object_url = get_URL().createObjectURL(blob);
  87. deletion_queue.push(object_url);
  88. return object_url;
  89. }
  90. , dispatch_all = function() {
  91. dispatch(filesaver, "writestart progress write writeend".split(" "));
  92. }
  93. // on any filesys errors revert to saving with object URLs
  94. , fs_error = function() {
  95. // don't create more object URLs than needed
  96. if (blob_changed || !object_url) {
  97. object_url = get_object_url(blob);
  98. }
  99. if (target_view) {
  100. target_view.location.href = object_url;
  101. } else {
  102. window.open(object_url, "_blank");
  103. }
  104. filesaver.readyState = filesaver.DONE;
  105. dispatch_all();
  106. }
  107. , abortable = function(func) {
  108. return function() {
  109. if (filesaver.readyState !== filesaver.DONE) {
  110. return func.apply(this, arguments);
  111. }
  112. };
  113. }
  114. , create_if_not_found = {create: true, exclusive: false}
  115. , slice
  116. ;
  117. filesaver.readyState = filesaver.INIT;
  118. if (!name) {
  119. name = "download";
  120. }
  121. if (can_use_save_link) {
  122. object_url = get_object_url(blob);
  123. // FF for Android has a nasty garbage collection mechanism
  124. // that turns all objects that are not pure javascript into 'deadObject'
  125. // this means `doc` and `save_link` are unusable and need to be recreated
  126. // `view` is usable though:
  127. doc = view.document;
  128. save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a");
  129. save_link.href = object_url;
  130. save_link.download = name;
  131. var event = doc.createEvent("MouseEvents");
  132. event.initMouseEvent(
  133. "click", true, false, view, 0, 0, 0, 0, 0
  134. , false, false, false, false, 0, null
  135. );
  136. save_link.dispatchEvent(event);
  137. filesaver.readyState = filesaver.DONE;
  138. dispatch_all();
  139. return;
  140. }
  141. // Object and web filesystem URLs have a problem saving in Google Chrome when
  142. // viewed in a tab, so I force save with application/octet-stream
  143. // http://code.google.com/p/chromium/issues/detail?id=91158
  144. if (view.chrome && type && type !== force_saveable_type) {
  145. slice = blob.slice || blob.webkitSlice;
  146. blob = slice.call(blob, 0, blob.size, force_saveable_type);
  147. blob_changed = true;
  148. }
  149. // Since I can't be sure that the guessed media type will trigger a download
  150. // in WebKit, I append .download to the filename.
  151. // https://bugs.webkit.org/show_bug.cgi?id=65440
  152. if (webkit_req_fs && name !== "download") {
  153. name += ".download";
  154. }
  155. if (type === force_saveable_type || webkit_req_fs) {
  156. target_view = view;
  157. }
  158. if (!req_fs) {
  159. fs_error();
  160. return;
  161. }
  162. fs_min_size += blob.size;
  163. req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  164. fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  165. var save = function() {
  166. dir.getFile(name, create_if_not_found, abortable(function(file) {
  167. file.createWriter(abortable(function(writer) {
  168. writer.onwriteend = function(event) {
  169. target_view.location.href = file.toURL();
  170. deletion_queue.push(file);
  171. filesaver.readyState = filesaver.DONE;
  172. dispatch(filesaver, "writeend", event);
  173. };
  174. writer.onerror = function() {
  175. var error = writer.error;
  176. if (error.code !== error.ABORT_ERR) {
  177. fs_error();
  178. }
  179. };
  180. "writestart progress write abort".split(" ").forEach(function(event) {
  181. writer["on" + event] = filesaver["on" + event];
  182. });
  183. writer.write(blob);
  184. filesaver.abort = function() {
  185. writer.abort();
  186. filesaver.readyState = filesaver.DONE;
  187. };
  188. filesaver.readyState = filesaver.WRITING;
  189. }), fs_error);
  190. }), fs_error);
  191. };
  192. dir.getFile(name, {create: false}, abortable(function(file) {
  193. // delete file if it already exists
  194. file.remove();
  195. save();
  196. }), abortable(function(ex) {
  197. if (ex.code === ex.NOT_FOUND_ERR) {
  198. save();
  199. } else {
  200. fs_error();
  201. }
  202. }));
  203. }), fs_error);
  204. }), fs_error);
  205. }
  206. , FS_proto = FileSaver.prototype
  207. , saveAs = function(blob, name) {
  208. return new FileSaver(blob, name);
  209. }
  210. ;
  211. FS_proto.abort = function() {
  212. var filesaver = this;
  213. filesaver.readyState = filesaver.DONE;
  214. dispatch(filesaver, "abort");
  215. };
  216. FS_proto.readyState = FS_proto.INIT = 0;
  217. FS_proto.WRITING = 1;
  218. FS_proto.DONE = 2;
  219. FS_proto.error =
  220. FS_proto.onwritestart =
  221. FS_proto.onprogress =
  222. FS_proto.onwrite =
  223. FS_proto.onabort =
  224. FS_proto.onerror =
  225. FS_proto.onwriteend =
  226. null;
  227. view.addEventListener("unload", process_deletion_queue, false);
  228. saveAs.unload = function() {
  229. process_deletion_queue();
  230. view.removeEventListener("unload", process_deletion_queue, false);
  231. };
  232. return saveAs;
  233. }(
  234. typeof self !== "undefined" && self
  235. || typeof window !== "undefined" && window
  236. || this.content
  237. ));
  238. // `self` is undefined in Firefox for Android content script context
  239. // while `this` is nsIContentFrameMessageManager
  240. // with an attribute `content` that corresponds to the window
  241. if (typeof module !== "undefined") module.exports = saveAs;