forked from twilson63/ngUpload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ng-upload.js
206 lines (187 loc) · 6.92 KB
/
ng-upload.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
// Version (see package.json)
// AngularJS simple file upload directive
// this directive uses an iframe as a target
// to enable the uploading of files without
// losing focus in the ng-app.
//
// <div ng-app="app">
// <div ng-controller="mainCtrl">
// <form ng-attr-action="/uploads"
// ng-upload="completed(content)">
// ng-upload-loading="loading()"
// <input type="file" name="avatar"></input>
// <input type="submit" value="Upload"
// ng-disabled="$isUploading"></input>
// </form>
// </div>
// </div>
//
// angular.module('app', ['ngUpload'])
// .controller('mainCtrl', function($scope) {
// $scope.loading = function() {
// console.log('loading...');
// }
// $scope.completed = function(content) {
// console.log(content);
// };
// });
//
angular.module('ngUpload', [])
.directive('uploadSubmit', ["$parse", function($parse) {
// Utility function to get the closest parent element with a given tag
function getParentNodeByTagName(element, tagName) {
element = angular.element(element);
var parent = element.parent();
tagName = tagName.toLowerCase();
if ( parent && parent[0].tagName.toLowerCase() === tagName ) {
return parent;
} else {
return !parent ? null : getParentNodeByTagName(parent, tagName);
}
}
return {
restrict: 'AC',
link: function(scope, element, attrs) {
element.bind('click', function($event) {
// prevent default behavior of click
if ($event) {
$event.preventDefault();
$event.stopPropagation();
}
if (element.attr('disabled')) { return; }
var form = getParentNodeByTagName(element, 'form');
form.triggerHandler('submit');
form[0].submit();
});
}
};
}])
.directive('ngUpload', ["$log", "$parse", "$document",
function ($log, $parse, $document) {
var iframeID = 1;
// Utility function to get meta tag with a given name attribute
function getMetaTagWithName(name) {
var head = $document.find('head');
var match;
angular.forEach(head.find('meta'), function(element) {
if ( element.getAttribute('name') === name ) {
match = element;
}
});
return angular.element(match);
}
return {
restrict: 'AC',
link: function (scope, element, attrs) {
// Give each directive instance a new id
iframeID++;
function setLoadingState(state) {
scope.$isUploading = state;
}
var options = {};
// Options (just 1 for now)
// Each option should be prefixed with 'upload-options-' or 'uploadOptions'
// {
// // add the Rails CSRF hidden input to form
// enableRailsCsrf: bool
// }
var fn = attrs.ngUpload ? $parse(attrs.ngUpload) : angular.noop;
var loading = attrs.ngUploadLoading ? $parse(attrs.ngUploadLoading) : null;
if ( attrs.hasOwnProperty( "uploadOptionsConvertHidden" ) ) {
// Allow blank or true
options.convertHidden = attrs.uploadOptionsConvertHidden != "false";
}
if ( attrs.hasOwnProperty( "uploadOptionsEnableRailsCsrf" ) ) {
// allow for blank or true
options.enableRailsCsrf = attrs.uploadOptionsEnableRailsCsrf != "false";
}
if ( attrs.hasOwnProperty( "uploadOptionsBeforeSubmit" ) ) {
options.beforeSubmit = $parse(attrs.uploadOptionsBeforeSubmit);
}
element.attr({
'target': 'upload-iframe-' + iframeID,
'method': 'post',
'enctype': 'multipart/form-data',
'encoding': 'multipart/form-data'
});
var iframe = angular.element(
'<iframe name="upload-iframe-' + iframeID + '" ' +
'border="0" width="0" height="0" ' +
'style="width:0px;height:0px;border:none;display:none">'
);
// If enabled, add csrf hidden input to form
if ( options.enableRailsCsrf ) {
var input = angular.element("<input />");
input.attr("class", "upload-csrf-token");
input.attr("type", "hidden");
input.attr("name", getMetaTagWithName('csrf-param').attr('content'));
input.val(getMetaTagWithName('csrf-token').attr('content'));
element.append(input);
}
element.after(iframe);
setLoadingState(false);
// Start upload
element.bind('submit', function uploadStart() {
var formController = scope[attrs.name];
// if form is invalid don't submit (e.g. keypress 13)
if(formController && formController.$invalid) return false;
// perform check before submit file
if (options.beforeSubmit && options.beforeSubmit(scope, {}) == false) return false;
// bind load after submit to prevent initial load triggering uploadEnd
iframe.bind('load', uploadEnd);
// If convertHidden option is enabled, set the value of hidden fields to the eval of the ng-model
if (options.convertHidden) {
angular.forEach(element.find('input'), function(el) {
var _el = angular.element(el);
if (_el.attr('ng-model') &&
_el.attr('type') &&
_el.attr('type') == 'hidden') {
_el.attr('value', scope.$eval(_el.attr('ng-model')));
}
});
}
if (!scope.$$phase) {
scope.$apply(function() {
if (loading) loading(scope);
setLoadingState(true);
});
} else {
if (loading) loading(scope);
setLoadingState(true);
}
});
// Finish upload
function uploadEnd() {
// unbind load after uploadEnd to prevent another load triggering uploadEnd
iframe.unbind('load');
if (!scope.$$phase) {
scope.$apply(function() {
setLoadingState(false);
});
} else {
setLoadingState(false);
}
// Get iframe body contents
var bodyContent = (iframe[0].contentDocument ||
iframe[0].contentWindow.document).body;
var content;
try {
content = angular.fromJson(bodyContent.innerText || bodyContent.textContent);
} catch (e) {
// Fall back to html if json parse failed
content = bodyContent.innerHTML;
$log.warn('Response is not valid JSON');
}
// if outside a digest cycle, execute the upload response function in the active scope
// else execute the upload response function in the current digest
if (!scope.$$phase) {
scope.$apply(function () {
fn(scope, { content: content});
});
} else {
fn(scope, { content: content});
}
}
}
};
}]);