Compare commits

..

7 Commits

Author SHA1 Message Date
dkhang97
1e5fb25e22 - Update Travis configuration; 2019-09-24 00:38:23 -07:00
dkhang97
7b9401e8f0 - Update karma version; 2019-08-15 15:49:06 -07:00
duykhang53
8878aa2f88 Update karma.conf.js 2019-08-15 15:36:32 -07:00
duykhang53
025162d345 Update .travis.yml 2019-08-15 15:24:42 -07:00
duykhang53
02b0c1db60 Update .travis.yml 2019-08-15 15:15:03 -07:00
duykhang53
732eb2d2a9 Update .travis.yml 2019-08-15 15:11:02 -07:00
dkhang97
6226188df3 - Implement of promise for filter function; 2019-08-15 14:46:09 -07:00
9 changed files with 5943 additions and 6324 deletions

View File

@@ -1,11 +1,13 @@
language: node_js language: node_js
node_js: node_js:
- "6" - "10.15.0"
sudo: required
services:
- xvfb
before_install: before_install:
- export CHROME_BIN=chromium-browser - google-chrome-stable --headless --disable-gpu --remote-debugging-port=9222 http://localhost &
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
script: script:
- npm run pretest - npm run pretest
@@ -15,6 +17,7 @@ after_success:
- ./node_modules/.bin/codecov - ./node_modules/.bin/codecov
addons: addons:
chrome: stable
firefox: "latest" firefox: "latest"
apt: apt:
sources: sources:

View File

@@ -67,7 +67,6 @@ Easy to use Angular2 directives for files upload ([demo](http://valor-software.g
5. `formatDataFunction` - Function to modify the request body. 'DisableMultipart' must be 'true' for this function to be called. 5. `formatDataFunction` - Function to modify the request body. 'DisableMultipart' must be 'true' for this function to be called.
6. `formatDataFunctionIsAsync` - Informs if the function sent in 'formatDataFunction' is asynchronous. Defaults to false. 6. `formatDataFunctionIsAsync` - Informs if the function sent in 'formatDataFunction' is asynchronous. Defaults to false.
7. `parametersBeforeFiles` - States if additional parameters should be appended before or after the file. Defaults to false. 7. `parametersBeforeFiles` - States if additional parameters should be appended before or after the file. Defaults to false.
8. `uploadFilesInSingleRequest` - If 'true', all files in the queue will be uploaded using one multipart request. Defaults to false. Notice this cannot be combined with 'disableMultipart' is 'true'.
### Events ### Events

View File

@@ -18,9 +18,8 @@ export class SimpleDemoComponent {
constructor (){ constructor (){
this.uploader = new FileUploader({ this.uploader = new FileUploader({
url: URL, url: URL,
disableMultipart: false, // 'DisableMultipart' must be 'true' for formatDataFunction to be called. disableMultipart: true, // 'DisableMultipart' must be 'true' for formatDataFunction to be called.
uploadFilesInSingleRequest: true, formatDataFunctionIsAsync: true,
formatDataFunctionIsAsync: false,
formatDataFunction: async (item) => { formatDataFunction: async (item) => {
return new Promise( (resolve, reject) => { return new Promise( (resolve, reject) => {
resolve({ resolve({

View File

@@ -48,6 +48,7 @@ module.exports = function (config) {
if (process.env.TRAVIS) { if (process.env.TRAVIS) {
configuration.browsers = ['Chrome_travis_ci']; configuration.browsers = ['Chrome_travis_ci'];
configuration.singleRun = true;
} }
if (process.env.SAUCE) { if (process.env.SAUCE) {

12014
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,9 +7,7 @@
"lite-server": "lite-server -c demo/bs-config.json", "lite-server": "lite-server -c demo/bs-config.json",
"demo.serve": "run-s build link demo.build lite-server", "demo.serve": "run-s build link demo.build lite-server",
"demo.gh-pages": "run-s build demo.build demo.deploy", "demo.gh-pages": "run-s build demo.build demo.deploy",
"demo.build": "ng build", "demo.build": "ng build -prod --aot",
"demo.build.watch": "ng build --watch",
"demo.buildOld": "ng build -prod --aot",
"demo.deploy": "gh-pages -d demo/dist", "demo.deploy": "gh-pages -d demo/dist",
"link": "ngm link -p src --here", "link": "ngm link -p src --here",
"lint": "exit 0", "lint": "exit 0",
@@ -86,8 +84,8 @@
"jasmine-core": "2.5.2", "jasmine-core": "2.5.2",
"jasmine-data-provider": "2.2.0", "jasmine-data-provider": "2.2.0",
"jasmine-spec-reporter": "3.2.0", "jasmine-spec-reporter": "3.2.0",
"karma": "1.4.0", "karma": "^4.2.0",
"karma-chrome-launcher": "^2.0.0", "karma-chrome-launcher": "^3.1.0",
"karma-cli": "^1.0.1", "karma-cli": "^1.0.1",
"karma-coverage-istanbul-reporter": "^1.3.0", "karma-coverage-istanbul-reporter": "^1.3.0",
"karma-jasmine": "^1.0.2", "karma-jasmine": "^1.0.2",

View File

@@ -1,12 +1,14 @@
import { Directive, EventEmitter, ElementRef, HostListener, Input, Output } from '@angular/core'; import { Directive, ElementRef, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { FileUploader, FileUploaderOptions } from './file-uploader.class'; import { FileUploader, FileUploaderOptions, FilterFunction } from './file-uploader.class';
@Directive({ selector: '[ng2FileDrop]' }) @Directive({ selector: '[ng2FileDrop]' })
export class FileDropDirective { export class FileDropDirective {
@Input() public uploader: FileUploader; @Input() public uploader: FileUploader;
// tslint:disable-next-line:no-input-rename
@Input('ng2FileFilter') public filter: FilterFunction['fn'];
@Output() public fileOver: EventEmitter<any> = new EventEmitter(); @Output() public fileOver: EventEmitter<any> = new EventEmitter();
@Output() public onFileDrop: EventEmitter<File[]> = new EventEmitter<File[]>(); @Output() public onFileDrop: EventEmitter<FileList> = new EventEmitter<FileList>();
protected element: ElementRef; protected element: ElementRef;
@@ -30,7 +32,10 @@ export class FileDropDirective {
} }
let options = this.getOptions(); let options = this.getOptions();
let filters = this.getFilters(); let filters = typeof this.filter === 'function' ? [{
name: 'ng2FileDropDirectiveFilter',
fn: this.filter
}, ...options.filters] : this.getFilters();
this._preventAndStop(event); this._preventAndStop(event);
this.uploader.addToQueue(transfer.files, options, filters); this.uploader.addToQueue(transfer.files, options, filters);
this.fileOver.emit(false); this.fileOver.emit(false);
@@ -61,11 +66,11 @@ export class FileDropDirective {
this.fileOver.emit(false); this.fileOver.emit(false);
} }
protected _getTransfer(event: any): any { protected _getTransfer(event: any): DragEvent['dataTransfer'] {
return event.dataTransfer ? event.dataTransfer : event.originalEvent.dataTransfer; // jQuery fix; return event.dataTransfer ? event.dataTransfer : event.originalEvent.dataTransfer; // jQuery fix;
} }
protected _preventAndStop(event: any): any { protected _preventAndStop(event: Event): any {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
} }

View File

@@ -1,10 +1,12 @@
import { Directive, EventEmitter, ElementRef, Input, HostListener, Output } from '@angular/core'; import { Directive, ElementRef, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { FileUploader } from './file-uploader.class'; import { FileUploader, FilterFunction } from './file-uploader.class';
@Directive({ selector: '[ng2FileSelect]' }) @Directive({ selector: '[ng2FileSelect]' })
export class FileSelectDirective { export class FileSelectDirective {
@Input() public uploader: FileUploader; @Input() public uploader: FileUploader;
// tslint:disable-next-line:no-input-rename
@Input('ng2FileFilter') public filter: FilterFunction['fn'];
@Output() public onFileSelected: EventEmitter<File[]> = new EventEmitter<File[]>(); @Output() public onFileSelected: EventEmitter<File[]> = new EventEmitter<File[]>();
protected element: ElementRef; protected element: ElementRef;
@@ -29,7 +31,10 @@ export class FileSelectDirective {
public onChange(): any { public onChange(): any {
let files = this.element.nativeElement.files; let files = this.element.nativeElement.files;
let options = this.getOptions(); let options = this.getOptions();
let filters = this.getFilters(); let filters = typeof this.filter === 'function' ? [{
name: 'ng2FileSelectDirectiveFilter',
fn: this.filter
}, ...options.filters] : this.getFilters();
this.uploader.addToQueue(files, options, filters); this.uploader.addToQueue(files, options, filters);
this.onFileSelected.emit(files); this.onFileSelected.emit(files);

View File

@@ -14,9 +14,9 @@ export interface Headers {
export type ParsedResponseHeaders = { [headerFieldName: string]: string }; export type ParsedResponseHeaders = { [headerFieldName: string]: string };
export type FilterFunction = { export interface FilterFunction {
name: string, name: string;
fn: (item?: FileLikeObject, options?: FileUploaderOptions) => boolean fn(this: FileUploader, item?: FileLikeObject, options?: FileUploaderOptions, queueIndex?: number): boolean | Promise<boolean>;
}; };
export interface FileUploaderOptions { export interface FileUploaderOptions {
@@ -39,7 +39,6 @@ export interface FileUploaderOptions {
parametersBeforeFiles?: boolean; parametersBeforeFiles?: boolean;
formatDataFunction?: Function; formatDataFunction?: Function;
formatDataFunctionIsAsync?: boolean; formatDataFunctionIsAsync?: boolean;
uploadFilesInSingleRequest?: boolean;
} }
export class FileUploader { export class FileUploader {
@@ -60,8 +59,7 @@ export class FileUploader {
removeAfterUpload: false, removeAfterUpload: false,
disableMultipart: false, disableMultipart: false,
formatDataFunction: (item: FileItem) => item._file, formatDataFunction: (item: FileItem) => item._file,
formatDataFunctionIsAsync: false, formatDataFunctionIsAsync: false
uploadFilesInSingleRequest : false
}; };
protected _failFilterIndex: number; protected _failFilterIndex: number;
@@ -73,6 +71,7 @@ export class FileUploader {
public setOptions(options: FileUploaderOptions): void { public setOptions(options: FileUploaderOptions): void {
this.options = Object.assign(this.options, options); this.options = Object.assign(this.options, options);
this.authToken = this.options.authToken; this.authToken = this.options.authToken;
this.authTokenHeader = this.options.authTokenHeader || 'Authorization'; this.authTokenHeader = this.options.authTokenHeader || 'Authorization';
this.autoUpload = this.options.autoUpload; this.autoUpload = this.options.autoUpload;
@@ -90,26 +89,30 @@ export class FileUploader {
this.options.filters.unshift({ name: 'mimeType', fn: this._mimeTypeFilter }); this.options.filters.unshift({ name: 'mimeType', fn: this._mimeTypeFilter });
} }
for (let i = 0; i < this.queue.length; i++) { for (const q of this.queue) {
this.queue[ i ].url = this.options.url; q.url = this.options.url;
} }
} }
public addToQueue(files: File[], options?: FileUploaderOptions, filters?: FilterFunction[] | string): void { public async addToQueue(files: FileList, options?: FileUploaderOptions, filters?: FilterFunction[] | string): Promise<void> {
let list: File[] = []; let list: File[] = [];
for (let file of files) { // tslint:disable-next-line:prefer-for-of
list.push(file); for (let i = 0; i < files.length; i++) {
list.push(files[i]);
} }
let arrayOfFilters = this._getFilters(filters); let arrayOfFilters = this._getFilters(filters);
let count = this.queue.length; let count = this.queue.length;
let addedFileItems: FileItem[] = []; let addedFileItems: FileItem[] = [];
list.map((some: File) => { let idx = 0;
for (const some of list) {
if (!options) { if (!options) {
options = this.options; options = this.options;
} }
let temp = new FileLikeObject(some); let temp = new FileLikeObject(some);
if (this._isValidFile(temp, arrayOfFilters, options)) { if (await this._isValidFile(temp, arrayOfFilters, options, idx++)) {
let fileItem = new FileItem(this, some, options); let fileItem = new FileItem(this, some, options);
addedFileItems.push(fileItem); addedFileItems.push(fileItem);
this.queue.push(fileItem); this.queue.push(fileItem);
@@ -118,7 +121,7 @@ export class FileUploader {
let filter = arrayOfFilters[this._failFilterIndex]; let filter = arrayOfFilters[this._failFilterIndex];
this._onWhenAddingFileFailed(temp, filter, options); this._onWhenAddingFileFailed(temp, filter, options);
} }
}); }
if (this.queue.length !== count) { if (this.queue.length !== count) {
this._onAfterAddingAll(addedFileItems); this._onAfterAddingAll(addedFileItems);
this.progress = this._getTotalProgress(); this.progress = this._getTotalProgress();
@@ -147,23 +150,15 @@ export class FileUploader {
} }
public uploadItem(value: FileItem): void { public uploadItem(value: FileItem): void {
this.uploadItems(new Array<FileItem>(value)); let index = this.getIndexOfItem(value);
}
public uploadItems(values: FileItem[]): void {
values.forEach(element => {
let index = this.getIndexOfItem(element);
let item = this.queue[index]; let item = this.queue[index];
item._prepareToUploading();
});
let transport = this.options.isHTML5 ? '_xhrTransport' : '_iframeTransport'; let transport = this.options.isHTML5 ? '_xhrTransport' : '_iframeTransport';
item._prepareToUploading();
if (this.isUploading) { if (this.isUploading) {
return; return;
} }
this.isUploading = true; this.isUploading = true;
(this as any)[ transport ](values); (this as any)[transport](item);
} }
public cancelItem(value: FileItem): void { public cancelItem(value: FileItem): void {
@@ -180,16 +175,9 @@ export class FileUploader {
if (!items.length) { if (!items.length) {
return; return;
} }
items.map((item: FileItem) => item._prepareToUploading()); items.map((item: FileItem) => item._prepareToUploading());
if (this.options.uploadFilesInSingleRequest){
this.uploadItems(items);
}
else{
items[0].upload(); items[0].upload();
} }
}
public cancelAll(): void { public cancelAll(): void {
let items = this.getNotUploadedItems(); let items = this.getNotUploadedItems();
@@ -291,9 +279,6 @@ export class FileUploader {
public _onCompleteItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): void { public _onCompleteItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): void {
item._onComplete(response, status, headers); item._onComplete(response, status, headers);
this.onCompleteItem(item, response, status, headers); this.onCompleteItem(item, response, status, headers);
if (!this.options.uploadFilesInSingleRequest)
{
let nextItem = this.getReadyItems()[0]; let nextItem = this.getReadyItems()[0];
this.isUploading = false; this.isUploading = false;
if (nextItem) { if (nextItem) {
@@ -304,18 +289,6 @@ export class FileUploader {
this.progress = this._getTotalProgress(); this.progress = this._getTotalProgress();
this._render(); this._render();
} }
}
public _onCompleteAllItems(items: FileItem[], response: string, status: number, headers: ParsedResponseHeaders): void {
items.forEach(item => {
item._onComplete(response, status, headers);
this.onCompleteItem(item, response, status, headers);
});
this.isUploading = false;
this.onCompleteAll();
this.progress = this._getTotalProgress();
this._render();
}
protected _headersGetter(parsedHeaders: ParsedResponseHeaders): any { protected _headersGetter(parsedHeaders: ParsedResponseHeaders): any {
return (name: any): any => { return (name: any): any => {
@@ -326,36 +299,22 @@ export class FileUploader {
}; };
} }
protected _xhrTransport(items: FileItem[]): any { protected _xhrTransport(item: FileItem): any {
let that = this; let that = this;
let firstItem = items[0]; let xhr = item._xhr = new XMLHttpRequest();
let xhr = firstItem._xhr = new XMLHttpRequest();
let sendable: any; let sendable: any;
items.forEach(item => {
this._onBeforeUploadItem(item); this._onBeforeUploadItem(item);
});
items.forEach(item => {
if (typeof item._file.size !== 'number') { if (typeof item._file.size !== 'number') {
throw new TypeError('The file specified is no longer valid'); throw new TypeError('The file specified is no longer valid');
} }
});
if (!this.options.disableMultipart) { if (!this.options.disableMultipart) {
sendable = new FormData(); sendable = new FormData();
items.forEach(item => {
this._onBuildItemForm(item, sendable); this._onBuildItemForm(item, sendable);
});
const appendFiles = () => {
items.forEach(item => {
sendable.append(item.alias, item._file, item.file.name)
});
};
const appendFile = () => sendable.append(item.alias, item._file, item.file.name);
if (!this.options.parametersBeforeFiles) { if (!this.options.parametersBeforeFiles) {
appendFiles(); appendFile();
} }
// For AWS, Additional Parameters must come BEFORE Files // For AWS, Additional Parameters must come BEFORE Files
@@ -363,66 +322,64 @@ export class FileUploader {
Object.keys(this.options.additionalParameter).forEach((key: string) => { Object.keys(this.options.additionalParameter).forEach((key: string) => {
let paramVal = this.options.additionalParameter[key]; let paramVal = this.options.additionalParameter[key];
// Allow an additional parameter to include the filename // Allow an additional parameter to include the filename
if (!this.options.uploadFilesInSingleRequest && typeof paramVal === 'string' && paramVal.indexOf('{{file_name}}') >= 0) { if (typeof paramVal === 'string' && paramVal.indexOf('{{file_name}}') >= 0) {
paramVal = paramVal.replace('{{file_name}}', firstItem.file.name); paramVal = paramVal.replace('{{file_name}}', item.file.name);
} }
sendable.append(key, paramVal); sendable.append(key, paramVal);
}); });
} }
if (this.options.parametersBeforeFiles) { if (this.options.parametersBeforeFiles) {
appendFiles(); appendFile();
} }
} else { } else {
sendable = this.options.formatDataFunction(firstItem); sendable = this.options.formatDataFunction(item);
} }
xhr.upload.onprogress = (event: any) => {
let progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
this._onProgressItem(item, progress);
};
xhr.onload = () => { xhr.onload = () => {
let headers = this._parseHeaders(xhr.getAllResponseHeaders()); let headers = this._parseHeaders(xhr.getAllResponseHeaders());
let response = this._transformResponse(xhr.response, headers); let response = this._transformResponse(xhr.response, headers);
let gist = this._isSuccessCode(xhr.status) ? 'Success' : 'Error'; let gist = this._isSuccessCode(xhr.status) ? 'Success' : 'Error';
let method = '_on' + gist + 'Item'; let method = '_on' + gist + 'Item';
items.forEach(item => {
(this as any)[method](item, response, xhr.status, headers); (this as any)[method](item, response, xhr.status, headers);
}); this._onCompleteItem(item, response, xhr.status, headers);
this._onCompleteAllItems(items, response, xhr.status, headers);
}; };
xhr.onerror = () => { xhr.onerror = () => {
let headers = this._parseHeaders(xhr.getAllResponseHeaders()); let headers = this._parseHeaders(xhr.getAllResponseHeaders());
let response = this._transformResponse(xhr.response, headers); let response = this._transformResponse(xhr.response, headers);
items.forEach(item => { this._onErrorItem(item, response, xhr.status, headers);
this._onErrorItem(firstItem, response, xhr.status, headers); this._onCompleteItem(item, response, xhr.status, headers);
});
this._onCompleteAllItems(items, response, xhr.status, headers);
}; };
xhr.onabort = () => { xhr.onabort = () => {
let headers = this._parseHeaders(xhr.getAllResponseHeaders()); let headers = this._parseHeaders(xhr.getAllResponseHeaders());
let response = this._transformResponse(xhr.response, headers); let response = this._transformResponse(xhr.response, headers);
items.forEach(item => { this._onCancelItem(item, response, xhr.status, headers);
this._onCancelItem(firstItem, response, xhr.status, headers); this._onCompleteItem(item, response, xhr.status, headers);
});
this._onCompleteAllItems(items, response, xhr.status, headers);
}; };
xhr.open(firstItem.method, firstItem.url, true); xhr.open(item.method, item.url, true);
xhr.withCredentials = firstItem.withCredentials; xhr.withCredentials = item.withCredentials;
if (this.options.headers) { if (this.options.headers) {
for (let header of this.options.headers) { for (let header of this.options.headers) {
xhr.setRequestHeader(header.name, header.value); xhr.setRequestHeader(header.name, header.value);
} }
} }
if (firstItem.headers.length) { if (item.headers.length) {
for (let header of firstItem.headers) { for (let header of item.headers) {
xhr.setRequestHeader(header.name, header.value); xhr.setRequestHeader(header.name, header.value);
} }
} }
if (this.authToken) { if (this.authToken) {
xhr.setRequestHeader(this.authTokenHeader, this.authToken); xhr.setRequestHeader(this.authTokenHeader, this.authToken);
} }
xhr.onreadystatechange = function () { xhr.onreadystatechange = function (): void {
if (xhr.readyState == XMLHttpRequest.DONE) { if (xhr.readyState === XMLHttpRequest.DONE) {
that.response.emit(xhr.responseText) that.response.emit(xhr.responseText);
}
} }
};
if (this.options.formatDataFunctionIsAsync) { if (this.options.formatDataFunctionIsAsync) {
sendable.then( sendable.then(
(result: any) => xhr.send(JSON.stringify(result)) (result: any) => xhr.send(JSON.stringify(result))
@@ -467,12 +424,18 @@ export class FileUploader {
return this.options.queueLimit === undefined || this.queue.length < this.options.queueLimit; return this.options.queueLimit === undefined || this.queue.length < this.options.queueLimit;
} }
protected _isValidFile(file: FileLikeObject, filters: FilterFunction[], options: FileUploaderOptions): boolean { protected async _isValidFile(file: FileLikeObject, filters: FilterFunction[], options: FileUploaderOptions, queueIndex: number): Promise<boolean> {
this._failFilterIndex = -1; this._failFilterIndex = -1;
return !filters.length ? true : filters.every((filter: FilterFunction) => {
for (const filter of filters) {
this._failFilterIndex++; this._failFilterIndex++;
return filter.fn.call(this, file, options);
}); if (!(await Promise.resolve(filter.fn.call(this, file, options, queueIndex)))) {
return false;
}
}
return true;
} }
protected _isSuccessCode(status: number): boolean { protected _isSuccessCode(status: number): boolean {