FileSaver.js 7.67 KB
Newer Older
1
/* FileSaver.js
XhmikosR's avatar
XhmikosR committed
2
 * A saveAs() FileSaver implementation.
3
 * 2015-03-04
4
 *
XhmikosR's avatar
XhmikosR committed
5
6
7
 * By Eli Grey, http://eligrey.com
 * License: X11/MIT
 *   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
8
9
10
 */

/*global self */
XhmikosR's avatar
XhmikosR committed
11
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
12

fat's avatar
fat committed
13
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
14
15

var saveAs = saveAs
16
  // IE 10+ (native saveAs)
XhmikosR's avatar
XhmikosR committed
17
18
  || (typeof navigator !== "undefined" &&
      navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))
19
  // Everyone else
20
21
  || (function(view) {
	"use strict";
22
	// IE <10 is explicitly unsupported
XhmikosR's avatar
XhmikosR committed
23
24
	if (typeof navigator !== "undefined" &&
	    /MSIE [1-9]\./.test(navigator.userAgent)) {
25
26
		return;
	}
27
28
	var
		  doc = view.document
XhmikosR's avatar
XhmikosR committed
29
		  // only get URL when necessary in case Blob.js hasn't overridden it yet
30
31
32
33
		, get_URL = function() {
			return view.URL || view.webkitURL || view;
		}
		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
XhmikosR's avatar
XhmikosR committed
34
		, can_use_save_link = "download" in save_link
35
36
37
38
39
40
41
42
43
44
		, click = function(node) {
			var event = doc.createEvent("MouseEvents");
			event.initMouseEvent(
				"click", true, false, view, 0, 0, 0, 0, 0
				, false, false, false, false, 0, null
			);
			node.dispatchEvent(event);
		}
		, webkit_req_fs = view.webkitRequestFileSystem
		, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
XhmikosR's avatar
XhmikosR committed
45
		, throw_outside = function(ex) {
46
47
48
49
50
51
			(view.setImmediate || view.setTimeout)(function() {
				throw ex;
			}, 0);
		}
		, force_saveable_type = "application/octet-stream"
		, fs_min_size = 0
XhmikosR's avatar
XhmikosR committed
52
53
54
55
		// See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
		// https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
		// for the reasoning behind the timeout and revocation flow
		, arbitrary_revoke_timeout = 500 // in ms
XhmikosR's avatar
XhmikosR committed
56
		, revoke = function(file) {
XhmikosR's avatar
XhmikosR committed
57
			var revoker = function() {
58
				if (typeof file === "string") { // file is an object URL
XhmikosR's avatar
XhmikosR committed
59
					get_URL().revokeObjectURL(file);
60
61
62
				} else { // file is a File
					file.remove();
				}
XhmikosR's avatar
XhmikosR committed
63
64
65
66
67
68
			};
			if (view.chrome) {
				revoker();
			} else {
				setTimeout(revoker, arbitrary_revoke_timeout);
			}
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
		}
		, 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) {
			// First try a.download, then web filesystem, then object URLs
			var
				  filesaver = this
				, type = blob.type
				, blob_changed = false
				, object_url
				, target_view
				, dispatch_all = function() {
					dispatch(filesaver, "writestart progress write writeend".split(" "));
				}
				// on any filesys errors revert to saving with object URLs
				, fs_error = function() {
					// don't create more object URLs than needed
					if (blob_changed || !object_url) {
XhmikosR's avatar
XhmikosR committed
99
						object_url = get_URL().createObjectURL(blob);
100
101
102
103
					}
					if (target_view) {
						target_view.location.href = object_url;
					} else {
XhmikosR's avatar
XhmikosR committed
104
105
106
107
108
						var new_tab = view.open(object_url, "_blank");
						if (new_tab == undefined && typeof safari !== "undefined") {
							//Apple do not allow window.open, see http://bit.ly/1kZffRI
							view.location.href = object_url
						}
XhmikosR's avatar
XhmikosR committed
109
					}
110
111
					filesaver.readyState = filesaver.DONE;
					dispatch_all();
XhmikosR's avatar
XhmikosR committed
112
					revoke(object_url);
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
				}
				, abortable = function(func) {
					return function() {
						if (filesaver.readyState !== filesaver.DONE) {
							return func.apply(this, arguments);
						}
					};
				}
				, create_if_not_found = {create: true, exclusive: false}
				, slice
			;
			filesaver.readyState = filesaver.INIT;
			if (!name) {
				name = "download";
			}
			if (can_use_save_link) {
XhmikosR's avatar
XhmikosR committed
129
				object_url = get_URL().createObjectURL(blob);
130
131
				save_link.href = object_url;
				save_link.download = name;
XhmikosR's avatar
XhmikosR committed
132
				click(save_link);
133
134
				filesaver.readyState = filesaver.DONE;
				dispatch_all();
XhmikosR's avatar
XhmikosR committed
135
				revoke(object_url);
136
137
				return;
			}
138
139
140
141
			// prepend BOM for UTF-8 XML and text/plain types
			if (/^\s*(?:text\/(?:plain|xml)|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
				blob = new Blob(["\ufeff", blob], {type: blob.type});
			}
142
143
144
			// Object and web filesystem URLs have a problem saving in Google Chrome when
			// viewed in a tab, so I force save with application/octet-stream
			// http://code.google.com/p/chromium/issues/detail?id=91158
XhmikosR's avatar
XhmikosR committed
145
146
			// Update: Google errantly closed 91158, I submitted it again:
			// https://code.google.com/p/chromium/issues/detail?id=389642
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
			if (view.chrome && type && type !== force_saveable_type) {
				slice = blob.slice || blob.webkitSlice;
				blob = slice.call(blob, 0, blob.size, force_saveable_type);
				blob_changed = true;
			}
			// Since I can't be sure that the guessed media type will trigger a download
			// in WebKit, I append .download to the filename.
			// https://bugs.webkit.org/show_bug.cgi?id=65440
			if (webkit_req_fs && name !== "download") {
				name += ".download";
			}
			if (type === force_saveable_type || webkit_req_fs) {
				target_view = view;
			}
			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_if_not_found, abortable(function(dir) {
					var save = function() {
						dir.getFile(name, create_if_not_found, abortable(function(file) {
							file.createWriter(abortable(function(writer) {
								writer.onwriteend = function(event) {
									target_view.location.href = file.toURL();
									filesaver.readyState = filesaver.DONE;
									dispatch(filesaver, "writeend", event);
XhmikosR's avatar
XhmikosR committed
175
									revoke(file);
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
								};
								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;

	return saveAs;
233
234
235
236
237
}(
	   typeof self !== "undefined" && self
	|| typeof window !== "undefined" && window
	|| this.content
));
238
239
240
241
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window

XhmikosR's avatar
XhmikosR committed
242
243
if (typeof module !== "undefined" && module.exports) {
  module.exports.saveAs = saveAs;
XhmikosR's avatar
XhmikosR committed
244
245
246
247
248
} else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
  define([], function() {
    return saveAs;
  });
}