-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangular-file.js
338 lines (289 loc) · 9.49 KB
/
angular-file.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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
175
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/**
* ur.file: Native HTML5-based file input bindings for AngularJS
*
* @version 0.9a
* @copyright (c) 2013 Union of RAD, LLC http://union-of-rad.com/
* @license: BSD
*/
/**
* The ur.file module implements native support for file uploads in AngularJS.
*/
angular.module('ur.file', []).config(['$provide', function($provide) {
/**
* XHR initialization, copied from Angular core, because it's buried inside $HttpProvider.
*/
var XHR = window.XMLHttpRequest || function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* Initializes XHR object with parameters from $httpBackend.
*/
function prepXHR(method, url, headers, callback, withCredentials, type, manager) {
var xhr = new XHR();
var status;
xhr.open(method, url, true);
if (type) {
xhr.type = type;
headers['Content-Type'] = type;
}
angular.forEach(headers, function(value, key) {
(value) ? xhr.setRequestHeader(key, value) : null;
});
manager.register(xhr);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
manager.unregister(xhr);
var response = xhr.response || xhr.responseText;
callback(status = status || xhr.status, response, xhr.getAllResponseHeaders());
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
return xhr;
}
/**
* Hook into $httpBackend to intercept requests containing files.
*/
$provide.decorator('$httpBackend', ['$delegate', '$window', 'uploadManager', function($delegate, $window, uploadManager) {
return function(method, url, post, callback, headers, timeout, wc) {
var containsFile = false, result = null, manager = uploadManager;
if (post && angular.isObject(post)) {
containsFile = hasFile(post);
}
if (angular.isObject(post)) {
angular.forEach({
name: 'X-File-Name',
size: 'X-File-Size',
lastModifiedDate: 'X-File-Last-Modified'
}, function(header, key) {
if (post && post[key]) {
if (!headers[header]) headers[header] = post[key];
}
});
}
if (post && post instanceof Blob) {
return prepXHR(method, url, headers, callback, wc, post.type, manager).send(post);
}
$delegate(method, url, post, callback, headers, timeout, wc);
};
}]);
/**
* Checks an object hash to see if it contains a File object, or, if legacy is true, checks to
* see if an object hash contains an <input type="file" /> element.
*/
var hasFile = function(data) {
for (var n in data) {
if (data[n] instanceof Blob) {
return true;
}
if ((angular.isObject(data[n]) || angular.isArray(data[n])) && hasFile(data[n])) {
return true;
}
}
return false;
};
/**
* Prevents $http from executing its default transformation behavior if the data to be
* transformed contains file data.
*/
$provide.decorator('$http', ['$delegate', function($delegate) {
var transformer = $delegate.defaults.transformRequest[0];
$delegate.defaults.transformRequest = [function(data) {
return data instanceof Blob ? data : transformer(data);
}];
return $delegate;
}]);
}]).service('fileHandler', ['$q', '$rootScope', function($q, $rootScope) {
return {
/**
* Loads a file as a data URL and returns a promise representing the file's value.
*/
load: function(file) {
var deferred = $q.defer();
var reader = angular.extend(new FileReader(), {
onload: function(e) {
deferred.resolve(e.target.result);
if (!$rootScope.$$phase) $rootScope.$apply();
},
onerror: function(e) {
deferred.reject(e);
if (!$rootScope.$$phase) $rootScope.$apply();
},
onabort: function(e) {
deferred.reject(e);
if (!$rootScope.$$phase) $rootScope.$apply();
}
// onprogress: Gee, it'd be great to get some progress support from $q...
});
reader.readAsDataURL(file);
return angular.extend(deferred.promise, {
abort: function() { reader.abort(); }
});
},
/**
* Returns the metadata from a File object, including the name, size and last modified date.
*/
meta: function(file) {
return {
name: file.name,
size: file.size,
lastModifiedDate: file.lastModifiedDate
};
},
/**
* Converts a File object or data URL to a Blob.
*/
toBlob: function(data) {
var extras = {};
if (data instanceof File) {
extras = this.meta(data);
data = data.toDataURL();
}
var parts = data.split(","), headers = parts[0].split(":"), body;
if (parts.length !== 2 || headers.length !== 2 || headers[0] !== "data") {
throw new Error("Invalid data URI.");
}
headers = headers[1].split(";");
body = (headers[1] === "base64") ? atob(parts[1]) : decodeURI(parts[1]);
var length = body.length, buffer = new ArrayBuffer(length), bytes = new Uint8Array(buffer);
for (var i = 0; i < length; i++) {
bytes[i] = body.charCodeAt(i);
}
return angular.extend(new Blob([bytes], { type: headers[0] }), extras);
}
};
}]).service('uploadManager', ['$rootScope', function($rootScope) {
angular.extend(this, {
id : null,
uploads: {},
capture: function(id) {
this.id = id;
this.uploads[id] = {
loaded: 0,
total: 0,
percent: 0,
object: null
};
},
register: function(xhr) {
if (this.id === null) {
return false;
}
xhr._idXhr = this.id;
this.id = null;
this.uploads[xhr._idXhr]['object'] = xhr;
var self = this;
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
self.uploads[xhr._idXhr]['loaded'] = e.loaded;
self.uploads[xhr._idXhr]['total'] = e.total;
self.uploads[xhr._idXhr]['percent'] = Math.round(e.loaded / e.total * 100);
$rootScope.$apply();
}
};
return true;
},
unregister: function(xhr) {
delete this.uploads[xhr._idXhr];
},
get: function(id) {
if (this.uploads[id]) {
return this.uploads[id];
}
return false;
},
abort: function(id) {
if (this.uploads[id]) {
return this.uploads[id]['object'].abort();
}
return false;
}
});
}]).directive('type', ['$parse', function urModelFileFactory($parse) {
/**
* Binding for file input elements
*/
return {
scope: false,
priority: 1,
require: "?ngModel",
link: function urFilePostLink(scope, element, attrs, ngModel) {
if (attrs.type.toLowerCase() !== 'file' || !ngModel) {
return;
}
element.bind('change', function(e) {
if (!e.target.files || !e.target.files.length || !e.target.files[0]) {
return true;
}
var index, fileData = attrs.multiple ? e.target.files : e.target.files[0];
ngModel.$render = function() {};
scope.$apply(function(scope) {
index = scope.$index;
$parse(attrs.ngModel).assign(scope, fileData);
});
scope.$index = index;
// @todo Make sure this can be replaced by ngChange.
// For that to work, this event handler must have a higher priority than the one
// defined by ngChange
attrs.change ? scope.$eval(attrs.change) : null;
});
}
};
}]).directive('dropTarget', ['$parse', 'fileHandler', function urDropTargetFactory($parse, fileHandler) {
return {
scope: false,
restrict: "EAC",
require: "?ngModel",
link: function urDropTargetLink(scope, element, attrs, ngModel) {
var multiple = attrs.multiple,
dropExpr = attrs.drop ? $parse(attrs.drop) : null,
modelExpr = attrs.ngModel ? $parse(attrs.ngModel) : null;
if (ngModel) ngModel.$render = function() {};
function stop(e) {
e.stopPropagation();
e.preventDefault();
}
var toIgnore = [], isOver = false;
element.bind("dragenter", function dragEnter(e) {
stop(e);
if (e.target === this && !isOver) {
if (attrs.overClass) element.addClass(attrs.overClass);
isOver = true;
return;
}
toIgnore.push(e.target);
});
element.bind("dragleave", function dragExit(e) {
stop(e);
if (toIgnore.length === 0 && isOver) {
if (attrs.overClass) element.removeClass(attrs.overClass);
isOver = false;
return;
}
toIgnore.pop();
});
element.bind("dragover", function(e) {
stop(e);
});
element.bind("drop", function(e) {
stop(e);
if (attrs.overClass) element.removeClass(attrs.overClass);
isOver = false;
e = e.originalEvent || e;
var files = e.dataTransfer.files;
if (!files.length) return;
files = multiple ? files : files[0];
if (modelExpr) modelExpr.assign(scope, files);
if (!dropExpr) return (scope.$$phase) ? null : scope.$apply();
var local = { $event: e };
local['$file' + (multiple ? 's' : '')] = files;
var result = function() { dropExpr(scope, local); };
(scope.$$phase) ? result() : scope.$apply(result);
});
}
};
}]);