-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
upload-btn.component.ts
378 lines (345 loc) · 11 KB
/
upload-btn.component.ts
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/**
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
*/
import { ENTER } from '@angular/cdk/keycodes';
import { HttpClient, HttpEvent, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import {
Component,
ElementRef,
Input,
NgZone,
OnInit,
OnDestroy,
Optional,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import { fromEvent, Observable, of, Subject, Subscription } from 'rxjs';
import { map, switchMap, takeUntil, tap } from 'rxjs/operators';
import { warn } from 'ng-zorro-antd/core/logger';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzUploadFile, NzUploadXHRArgs, ZipButtonOptions } from './interface';
@Component({
selector: '[nz-upload-btn]',
exportAs: 'nzUploadBtn',
templateUrl: './upload-btn.component.html',
host: {
class: 'ant-upload',
'[attr.tabindex]': '"0"',
'[attr.role]': '"button"',
'[class.ant-upload-disabled]': 'options.disabled',
'(drop)': 'onFileDrop($event)',
'(dragover)': 'onFileDrop($event)'
},
preserveWhitespaces: false,
encapsulation: ViewEncapsulation.None
})
export class NzUploadBtnComponent implements OnInit, OnDestroy {
reqs: { [key: string]: Subscription } = {};
private destroy = false;
private destroy$ = new Subject<void>();
@ViewChild('file', { static: true }) file!: ElementRef<HTMLInputElement>;
@Input() options!: ZipButtonOptions;
onClick(): void {
if (this.options.disabled || !this.options.openFileDialogOnClick) {
return;
}
this.file.nativeElement.click();
}
// skip safari bug
onFileDrop(e: DragEvent): void {
if (this.options.disabled || e.type === 'dragover') {
e.preventDefault();
return;
}
if (this.options.directory) {
this.traverseFileTree(e.dataTransfer!.items);
} else {
const files: File[] = Array.prototype.slice
.call(e.dataTransfer!.files)
.filter((file: File) => this.attrAccept(file, this.options.accept));
if (files.length) {
this.uploadFiles(files);
}
}
e.preventDefault();
}
onChange(e: Event): void {
if (this.options.disabled) {
return;
}
const hie = e.target as HTMLInputElement;
this.uploadFiles(hie.files!);
hie.value = '';
}
private traverseFileTree(files: DataTransferItemList): void {
const _traverseFileTree = (item: NzSafeAny, path: string): void => {
if (item.isFile) {
item.file((file: File) => {
if (this.attrAccept(file, this.options.accept)) {
this.uploadFiles([file]);
}
});
} else if (item.isDirectory) {
const dirReader = item.createReader();
dirReader.readEntries((entries: NzSafeAny) => {
for (const entrieItem of entries) {
_traverseFileTree(entrieItem, `${path}${item.name}/`);
}
});
}
};
for (const file of files as NzSafeAny) {
_traverseFileTree(file.webkitGetAsEntry(), '');
}
}
private attrAccept(file: File, acceptedFiles?: string | string[]): boolean {
if (file && acceptedFiles) {
const acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(',');
const fileName = `${file.name}`;
const mimeType = `${file.type}`;
const baseMimeType = mimeType.replace(/\/.*$/, '');
return acceptedFilesArray.some(type => {
const validType = type.trim();
if (validType.charAt(0) === '.') {
return (
fileName
.toLowerCase()
.indexOf(validType.toLowerCase(), fileName.toLowerCase().length - validType.toLowerCase().length) !== -1
);
} else if (/\/\*$/.test(validType)) {
// This is something like a image/* mime type
return baseMimeType === validType.replace(/\/.*$/, '');
}
return mimeType === validType;
});
}
return true;
}
private attachUid(file: NzUploadFile): NzUploadFile {
if (!file.uid) {
file.uid = Math.random().toString(36).substring(2);
}
return file;
}
uploadFiles(fileList: FileList | File[]): void {
let filters$: Observable<NzUploadFile[]> = of(Array.prototype.slice.call(fileList));
if (this.options.filters) {
this.options.filters.forEach(f => {
filters$ = filters$.pipe(
switchMap(list => {
const fnRes = f.fn(list);
return fnRes instanceof Observable ? fnRes : of(fnRes);
})
);
});
}
filters$.subscribe(
list => {
list.forEach((file: NzUploadFile) => {
this.attachUid(file);
this.upload(file, list);
});
},
e => {
warn(`Unhandled upload filter error`, e);
}
);
}
private upload(file: NzUploadFile, fileList: NzUploadFile[]): void {
if (!this.options.beforeUpload) {
return this.post(file);
}
const before = this.options.beforeUpload(file, fileList);
if (before instanceof Observable) {
before.subscribe(
(processedFile: NzUploadFile) => {
const processedFileType = Object.prototype.toString.call(processedFile);
if (processedFileType === '[object File]' || processedFileType === '[object Blob]') {
this.attachUid(processedFile);
this.post(processedFile);
} else if (typeof processedFile === 'boolean' && processedFile !== false) {
this.post(file);
}
},
e => {
warn(`Unhandled upload beforeUpload error`, e);
}
);
} else if (before !== false) {
return this.post(file);
}
}
private post(file: NzUploadFile): void {
if (this.destroy) {
return;
}
let process$: Observable<string | Blob | File | NzUploadFile> = of(file);
let transformedFile: string | Blob | File | NzUploadFile | undefined;
const opt = this.options;
const { uid } = file;
const { action, data, headers, transformFile } = opt;
const args: NzUploadXHRArgs = {
action: typeof action === 'string' ? action : '',
name: opt.name,
headers,
file,
postFile: file,
data,
withCredentials: opt.withCredentials,
onProgress: opt.onProgress
? e => {
opt.onProgress!(e, file);
}
: undefined,
onSuccess: (ret, xhr) => {
this.clean(uid);
opt.onSuccess!(ret, file, xhr);
},
onError: xhr => {
this.clean(uid);
opt.onError!(xhr, file);
}
};
if (typeof action === 'function') {
const actionResult = (action as (file: NzUploadFile) => string | Observable<string>)(file);
if (actionResult instanceof Observable) {
process$ = process$.pipe(
switchMap(() => actionResult),
map(res => {
args.action = res;
return file;
})
);
} else {
args.action = actionResult;
}
}
if (typeof transformFile === 'function') {
const transformResult = transformFile(file);
process$ = process$.pipe(
switchMap(() => (transformResult instanceof Observable ? transformResult : of(transformResult))),
tap(newFile => (transformedFile = newFile))
);
}
if (typeof data === 'function') {
const dataResult = (data as (file: NzUploadFile) => {} | Observable<{}>)(file);
if (dataResult instanceof Observable) {
process$ = process$.pipe(
switchMap(() => dataResult),
map(res => {
args.data = res;
return transformedFile ?? file;
})
);
} else {
args.data = dataResult;
}
}
if (typeof headers === 'function') {
const headersResult = (headers as (file: NzUploadFile) => {} | Observable<{}>)(file);
if (headersResult instanceof Observable) {
process$ = process$.pipe(
switchMap(() => headersResult),
map(res => {
args.headers = res;
return transformedFile ?? file;
})
);
} else {
args.headers = headersResult;
}
}
process$.subscribe(newFile => {
args.postFile = newFile;
const req$ = (opt.customRequest || this.xhr).call(this, args);
if (!(req$ instanceof Subscription)) {
warn(`Must return Subscription type in '[nzCustomRequest]' property`);
}
this.reqs[uid] = req$;
opt.onStart!(file);
});
}
private xhr(args: NzUploadXHRArgs): Subscription {
const formData = new FormData();
if (args.data) {
Object.keys(args.data).map(key => {
formData.append(key, args.data![key]);
});
}
formData.append(args.name!, args.postFile as NzSafeAny);
if (!args.headers) {
args.headers = {};
}
if (args.headers['X-Requested-With'] !== null) {
args.headers['X-Requested-With'] = `XMLHttpRequest`;
} else {
delete args.headers['X-Requested-With'];
}
const req = new HttpRequest('POST', args.action!, formData, {
reportProgress: true,
withCredentials: args.withCredentials,
headers: new HttpHeaders(args.headers)
});
return this.http.request(req).subscribe(
(event: HttpEvent<NzSafeAny>) => {
if (event.type === HttpEventType.UploadProgress) {
if (event.total! > 0) {
(event as NzSafeAny).percent = (event.loaded / event.total!) * 100;
}
args.onProgress!(event, args.file);
} else if (event instanceof HttpResponse) {
args.onSuccess!(event.body, args.file, event);
}
},
err => {
this.abort(args.file);
args.onError!(err, args.file);
}
);
}
private clean(uid: string): void {
const req$ = this.reqs[uid];
if (req$ instanceof Subscription) {
req$.unsubscribe();
}
delete this.reqs[uid];
}
abort(file?: NzUploadFile): void {
if (file) {
this.clean(file && file.uid);
} else {
Object.keys(this.reqs).forEach(uid => this.clean(uid));
}
}
constructor(private ngZone: NgZone, @Optional() private http: HttpClient, private elementRef: ElementRef) {
if (!http) {
throw new Error(`Not found 'HttpClient', You can import 'HttpClientModule' in your root module.`);
}
}
ngOnInit(): void {
// Caretaker note: `input[type=file].click()` will open a native OS file picker,
// it doesn't require Angular to run `ApplicationRef.tick()`.
this.ngZone.runOutsideAngular(() => {
fromEvent(this.elementRef.nativeElement, 'click')
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.onClick());
fromEvent<KeyboardEvent>(this.elementRef.nativeElement, 'keydown')
.pipe(takeUntil(this.destroy$))
.subscribe(event => {
if (this.options.disabled) {
return;
}
if (event.key === 'Enter' || event.keyCode === ENTER) {
this.onClick();
}
});
});
}
ngOnDestroy(): void {
this.destroy = true;
this.destroy$.next();
this.abort();
}
}