Compare commits

..

3 Commits

Author SHA1 Message Date
Ravinder Payal 36ebe449b0 Update file-uploader.class.ts
added (line:280) response pusher (observer.next) for pushing the reponse to subscriber
2017-02-04 21:42:14 +05:30
Ravinder Payal f72aa05e4e Update file-item.class.ts 2017-02-04 21:38:38 +05:30
Ravinder Payal 5b26793662 Create operator.ts
Contains required rxjs operators' import
2017-02-04 21:23:58 +05:30
40 changed files with 8341 additions and 19449 deletions
+2 -4
View File
@@ -1,13 +1,11 @@
language: node_js language: node_js
node_js: node_js:
- "10" - "6"
services:
- xvfb
before_install: before_install:
- export CHROME_BIN=chromium-browser - export CHROME_BIN=chromium-browser
- export DISPLAY=:99.0 - export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
script: script:
- npm run pretest - npm run pretest
-25
View File
@@ -1,28 +1,3 @@
<a name="1.3.0"></a>
# [1.3.0](https://github.com/valor-software/ng2-file-upload/compare/v1.2.0...v1.3.0) (2017-11-25)
### Features
* **file-upload:** Add response and function to modify the request body ([#901](https://github.com/valor-software/ng2-file-upload/pull/901))
* **file-upload** add file type .zip ([#911](https://github.com/valor-software/ng2-file-upload/pull/911))
### Bug Fixes
* **file-uploader** Update: setOptions ([#904](https://github.com/valor-software/ng2-file-upload/pull/904))
* **docs** Fix correct path for isHTML5 option ([#844](https://github.com/valor-software/ng2-file-upload/pull/844))
* **docs** Added onFileDrop() event to documentation ([#857](https://github.com/valor-software/ng2-file-upload/pull/857))
<a name="1.2.1"></a>
## [1.2.1](https://github.com/valor-software/ng2-file-upload/compare/v1.2.0...v1.2.1) (2017-04-10)
### Features
* **package:** relaxed peer dependencies to allow ng v4 ([#713](https://github.com/valor-software/ng2-file-upload/issues/713)) ([7704e0e](https://github.com/valor-software/ng2-file-upload/commit/7704e0e))
<a name="1.2.0"></a> <a name="1.2.0"></a>
# [1.2.0](https://github.com/valor-software/ng2-file-upload/compare/v1.1.3-0...v1.2.0) (2017-01-17) # [1.2.0](https://github.com/valor-software/ng2-file-upload/compare/v1.1.3-0...v1.2.0) (2017-01-17)
+2 -33
View File
@@ -19,39 +19,12 @@ Easy to use Angular2 directives for files upload ([demo](http://valor-software.g
3. More information regarding using of ***ng2-file-upload*** is located in 3. More information regarding using of ***ng2-file-upload*** is located in
[demo](http://valor-software.github.io/ng2-file-upload/) and [demo sources](https://github.com/valor-software/ng2-file-upload/tree/master/demo). [demo](http://valor-software.github.io/ng2-file-upload/) and [demo sources](https://github.com/valor-software/ng2-file-upload/tree/master/demo).
## Using ***ng2-file-upload*** in a project
1. Install as shown in the above section.
2. Import `FileUploadModule` into the module that declares the component using ***ng2-file-upload***:
```import { FileUploadModule } from 'ng2-file-upload';```
3. Add it to `[imports]` under `@NgModule`:
```imports: [ ... FileUploadModule, ... ]```
4. Import `FileUploader` into the component:
```import { FileUploader } from 'ng2-file-upload';```
5. Create a variable for the API url:
```const URL = 'path_to_api';```
6. Initialize it:
```public uploader:FileUploader = new FileUploader({url: URL}); ```
## API for `ng2FileSelect` ## API for `ng2FileSelect`
### Properties ### Properties
- `uploader` - (`FileUploader`) - uploader object. See using in [demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.ts) - `uploader` - (`FileUploader`) - uploader object. See using in [demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.ts)
### Events
- `onFileSelected` - fires when files are selected and added to the uploader queue
## API for `ng2FileDrop` ## API for `ng2FileDrop`
### Properties ### Properties
@@ -63,21 +36,17 @@ Easy to use Angular2 directives for files upload ([demo](http://valor-software.g
1. `url` - URL of File Uploader's route 1. `url` - URL of File Uploader's route
2. `authToken` - Auth token that will be applied as 'Authorization' header during file send. 2. `authToken` - Auth token that will be applied as 'Authorization' header during file send.
3. `disableMultipart` - If 'true', disable using a multipart form for file upload and instead stream the file. Some APIs (e.g. Amazon S3) may expect the file to be streamed rather than sent via a form. Defaults to false. 3. `disableMultipart` - If 'true', disable using a multipart form for file upload and instead stream the file. Some APIs (e.g. Amazon S3) may expect the file to be streamed rather than sent via a form. Defaults to false.
4. `itemAlias` - item alias (form name redefinition) 4. `itemAlias` - item alias (form name redefenition)
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.
7. `parametersBeforeFiles` - States if additional parameters should be appended before or after the file. Defaults to false.
### Events ### Events
- `fileOver` - it fires during 'over' and 'out' events for Drop Area; returns `boolean`: `true` if file is over Drop Area, `false` in case of out. - `fileOver` - it fires during 'over' and 'out' events for Drop Area; returns `boolean`: `true` if file is over Drop Area, `false` in case of out.
See using in [ts demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.ts) and See using in [ts demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.ts) and
[html demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.html) [html demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.html)
- `onFileDrop` - it fires after a file has been dropped on a Drop Area; you can pass in `$event` to get the list of files that were dropped. i.e. `(onFileDrop)="dropped($event)"`
# Troubleshooting # Troubleshooting
Please follow these guidelines when reporting bugs and feature requests: Please follow this guidelines when reporting bugs and feature requests:
1. Use [GitHub Issues](https://github.com/valor-software/ng2-file-upload/issues) board to report bugs and feature requests (not our email address) 1. Use [GitHub Issues](https://github.com/valor-software/ng2-file-upload/issues) board to report bugs and feature requests (not our email address)
2. Please **always** write steps to reproduce the error. That way we can focus on fixing the bug, not scratching our heads trying to reproduce it. 2. Please **always** write steps to reproduce the error. That way we can focus on fixing the bug, not scratching our heads trying to reproduce it.
+57
View File
@@ -0,0 +1,57 @@
{
"project": {
"name": "ng2-file-upload"
},
"apps": [
{
"root": "demo/src",
"outDir": "demo/dist",
"assets": [
"assets"
],
"index": "index.html",
"main": "main.ts",
"test": "../../scripts/test.ts",
"tsconfig": "tsconfig.json",
"prefix": "",
"mobile": false,
"styles": [
],
"scripts": [
],
"environments": {
"source": "environments/environment.ts",
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"addons": [],
"packages": [],
"e2e": {
"protractor": {
"config": "protractor.conf.js"
}
},
"test": {
"karma": {
"config": "karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"prefixInterfaces": false,
"inline": {
"style": false,
"template": false
},
"spec": {
"class": false,
"component": true,
"directive": true,
"module": false,
"pipe": true,
"service": true
}
}
}
-112
View File
@@ -1,112 +0,0 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ng2-file-upload": {
"root": ".",
"sourceRoot": "src",
"projectType": "library",
"architect": {
"build": {
"builder": "@angular-devkit/build-ng-packagr:build",
"options": {
"tsConfig": "src/tsconfig.json",
"project": "src/ng-package.json"
}
}
}
},
"ng2-file-upload-demo": {
"root": "demo",
"sourceRoot": "demo/src",
"projectType": "application",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "demo/dist",
"index": "demo/src/index.html",
"main": "demo/src/main.ts",
"tsConfig": "demo/src/tsconfig.json",
"assets": [
"demo/src/assets"
],
"styles": [],
"scripts": []
},
"configurations": {
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"fileReplacements": [
{
"replace": "demo/src/environments/environment.ts",
"with": "demo/src/environments/environment.prod.ts"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "ng2-file-upload-demo:build"
},
"configurations": {
"production": {
"browserTarget": "ng2-file-upload-demo:build:production"
}
}
}
}
},
"ng2-file-upload-test": {
"root": ".",
"sourceRoot": "test",
"projectType": "library",
"architect": {
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "test/test.ts",
"karmaConfig": "test/karma.conf.js",
"scripts": [],
"styles": [],
"tsConfig": "test/tsconfig.json"
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.json",
"demo/src/tsconfig.json",
"test/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "ng2-file-upload-demo",
"schematics": {
"@schematics/angular:component": {
"prefix": "",
"styleext": "css"
},
"@schematics/angular:directive": {
"prefix": ""
}
}
}
-12
View File
@@ -1,12 +0,0 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11 # For IE 9-11 support, remove 'not'.
+1 -1
View File
@@ -3,7 +3,7 @@ import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser'; import { BrowserModule } from '@angular/platform-browser';
import { TabsModule } from 'ngx-bootstrap/tabs'; import { TabsModule } from 'ng2-bootstrap';
import { FileUploadModule } from 'ng2-file-upload'; import { FileUploadModule } from 'ng2-file-upload';
import { AppComponent } from './app.component'; import { AppComponent } from './app.component';
@@ -5,9 +5,9 @@ let doc = require('html-loader!markdown-loader!../../doc.md');
let tabDesc:Array<any> = [ let tabDesc:Array<any> = [
{ {
heading: 'Simple', heading: 'Simple',
ts: require('!!raw-loader!./file-upload/simple-demo.ts').default, ts: require('!!raw-loader?lang=typescript!./file-upload/simple-demo.ts'),
html: require('!!raw-loader!./file-upload/simple-demo.html').default, html: require('!!raw-loader?lang=markup!./file-upload/simple-demo.html'),
js: require('!!raw-loader!./file-upload/file-catcher.js').default js: require('!!raw-loader?lang=javascript!./file-upload/file-catcher.js')
} }
]; ];
@@ -61,8 +61,8 @@
<tbody> <tbody>
<tr *ngFor="let item of uploader.queue"> <tr *ngFor="let item of uploader.queue">
<td><strong>{{ item?.file?.name }}</strong></td> <td><strong>{{ item?.file?.name }}</strong></td>
<td *ngIf="uploader.options.isHTML5" nowrap>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</td> <td *ngIf="uploader.isHTML5" nowrap>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</td>
<td *ngIf="uploader.options.isHTML5"> <td *ngIf="uploader.isHTML5">
<div class="progress" style="margin-bottom: 0;"> <div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': item.progress + '%' }"></div> <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': item.progress + '%' }"></div>
</div> </div>
@@ -115,16 +115,4 @@
</div> </div>
<br><br>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Response</div>
<div class="panel-body">
{{ response }}
</div>
</div>
</div>
</div>
</div> </div>
@@ -9,36 +9,9 @@ const URL = 'https://evening-anchorage-3159.herokuapp.com/api/';
templateUrl: './simple-demo.html' templateUrl: './simple-demo.html'
}) })
export class SimpleDemoComponent { export class SimpleDemoComponent {
public uploader:FileUploader = new FileUploader({url: URL});
uploader:FileUploader; public hasBaseDropZoneOver:boolean = false;
hasBaseDropZoneOver:boolean; public hasAnotherDropZoneOver:boolean = false;
hasAnotherDropZoneOver:boolean;
response:string;
constructor (){
this.uploader = new FileUploader({
url: URL,
disableMultipart: true, // 'DisableMultipart' must be 'true' for formatDataFunction to be called.
formatDataFunctionIsAsync: true,
formatDataFunction: async (item) => {
return new Promise( (resolve, reject) => {
resolve({
name: item._file.name,
length: item._file.size,
contentType: item._file.type,
date: new Date()
});
});
}
});
this.hasBaseDropZoneOver = false;
this.hasAnotherDropZoneOver = false;
this.response = '';
this.uploader.response.subscribe( res => this.response = res );
}
public fileOverBase(e:any):void { public fileOverBase(e:any):void {
this.hasBaseDropZoneOver = e; this.hasBaseDropZoneOver = e;
-8
View File
@@ -25,13 +25,6 @@ import { FileSelectDirective, FileDropDirective, FileUploader } from 'ng2-file-u
1. `url` - URL of File Uploader's route 1. `url` - URL of File Uploader's route
2. `authToken` - auth token that will be applied as 'Authorization' header during file send. 2. `authToken` - auth token that will be applied as 'Authorization' header during file send.
3. `disableMultipart` - If 'true', disable using a multipart form for file upload and instead stream the file. Some APIs (e.g. Amazon S3) may expect the file to be streamed rather than sent via a form. Defaults to false. 3. `disableMultipart` - If 'true', disable using a multipart form for file upload and instead stream the file. Some APIs (e.g. Amazon S3) may expect the file to be streamed rather than sent via a form. Defaults to false.
4. `itemAlias` - item alias (form name redefenition)
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.
7. `parametersBeforeFiles` - States if additional parameters should be appended before or after the file. Defaults to false.
### Events
- `onFileSelected` - fires when files are selected and added to the uploader queue
## FileDrop API ## FileDrop API
@@ -44,4 +37,3 @@ import { FileSelectDirective, FileDropDirective, FileUploader } from 'ng2-file-u
- `fileOver` - it fires during 'over' and 'out' events for Drop Area; returns `boolean`: `true` if file is over Drop Area, `false` in case of out. - `fileOver` - it fires during 'over' and 'out' events for Drop Area; returns `boolean`: `true` if file is over Drop Area, `false` in case of out.
See using in [ts demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.ts) and See using in [ts demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.ts) and
[html demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.html) [html demo](https://github.com/valor-software/ng2-file-upload/blob/master/demo/components/file-upload/simple-demo.html)
- `onFileDrop` - it fires after a file has been dropped on a Drop Area; you can pass in `$event` to get the list of files that were dropped. i.e. `(onFileDrop)="dropped($event)"`
+1 -1
View File
@@ -1,4 +1,4 @@
import '../../scripts/polyfills.ts'; import './polyfills.ts';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core'; import { enableProdMode } from '@angular/core';
+10 -13
View File
@@ -1,25 +1,22 @@
{ {
"compilerOptions": { "compilerOptions": {
"baseUrl": ".",
"declaration": false, "declaration": false,
"downlevelIteration": true,
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"noEmitHelpers": false, "noEmitHelpers" :true,
"lib": ["es6", "dom"], "lib": ["es6", "dom"],
"types": [
"jasmine",
"webpack"
],
"mapRoot": "./", "mapRoot": "./",
"module": "esnext", "module": "es6",
"moduleResolution": "node", "moduleResolution": "node",
"outDir": "../temp/out-tsc", "outDir": "../temp/out-tsc",
"sourceMap": true, "sourceMap": true,
"target": "es2015" "target": "es5",
}, "typeRoots": [
"files": [ "../node_modules/@types"
"../../scripts/typings.d.ts",
"main.ts",
"../../scripts/polyfills.ts"
],
"exclude": [
"**/*.spec.ts"
] ]
} }
}
+16
View File
@@ -0,0 +1,16 @@
// Typings reference file, you can add your own global typings here
// https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html
// tslint:disable
declare const System: any;
declare const ENV:string;
// google code-prettify
declare const PR:any;
declare const require:any;
declare const global:any;
declare module jasmine {
interface Matchers {
toHaveCssClass(expected: any): boolean;
}
}
+28 -23
View File
@@ -1,42 +1,47 @@
// Karma configuration file, see link for more information // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html // https://karma-runner.github.io/0.13/config/configuration-file.html
const customLaunchers = require('./sauce-browsers').customLaunchers; const customLaunchers = require('./scripts/sauce-browsers').customLaunchers;
module.exports = function (config) { module.exports = function (config) {
const configuration = { const configuration = {
basePath: '', basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'], frameworks: ['jasmine', 'angular-cli'],
plugins: [ plugins: [
require('karma-jasmine'), require('karma-jasmine'),
require('karma-chrome-launcher'), require('karma-chrome-launcher'),
require('karma-coverage-istanbul-reporter'), require('karma-remap-istanbul'),
require('@angular-devkit/build-angular/plugins/karma') require('angular-cli/plugins/karma')
], ],
coverageIstanbulReporter: { files: [
dir: require('path').join(__dirname, '../coverage'), reports: [ 'html', 'lcovonly' ], {pattern: './scripts/test.ts', watched: false}
fixWebpackSourcePaths: false ],
preprocessors: {
'./scripts/test.ts': ['angular-cli']
}, },
remapIstanbulReporter: {
reporters: ['dots', 'coverage-istanbul'], reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov'
}
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['dots', 'karma-remap-istanbul']
: ['dots'],
port: 9876, port: 9876,
colors: true, colors: true,
logLevel: config.LOG_INFO, logLevel: config.LOG_INFO,
autoWatch: true, autoWatch: true,
browsers: ['ChromeHeadless'], browsers: ['Chrome'],
browserNoActivityTimeout: 20000, singleRun: false,
browserDisconnectTolerance: 2,
browserDisconnectTimeout: 5000,
singleRun: true,
customLaunchers: { customLaunchers: {
Chrome_travis_ci: { Chrome_travis_ci: {
base: 'ChromeHeadless', base: 'Chrome',
flags: [ flags: ['--no-sandbox']
'--headless',
'--disable-gpu',
'--no-sandbox',
'--remote-debugging-port=9222'
]
} }
}, },
mime: { 'text/x-typescript': ['ts','tsx'] }, mime: { 'text/x-typescript': ['ts','tsx'] },
@@ -67,10 +72,10 @@ module.exports = function (config) {
}, },
public: 'public' public: 'public'
}; };
configuration.captureTimeout = 60000; configuration.captureTimeout = 0;
configuration.customLaunchers = customLaunchers(); configuration.customLaunchers = customLaunchers();
configuration.browsers = Object.keys(configuration.customLaunchers); configuration.browsers = Object.keys(configuration.customLaunchers);
configuration.concurrency = 4; configuration.concurrency = 3;
configuration.browserDisconnectTolerance = 2; configuration.browserDisconnectTolerance = 2;
configuration.browserNoActivityTimeout = 20000; configuration.browserNoActivityTimeout = 20000;
configuration.browserDisconnectTimeout = 5000; configuration.browserDisconnectTimeout = 5000;
-18533
View File
File diff suppressed because it is too large Load Diff
+50 -46
View File
@@ -1,27 +1,30 @@
{ {
"name": "ng2-file-upload-base", "name": "ng2-file-upload-base",
"version": "1.3.0", "version": "1.2.0",
"private": true, "private": true,
"description": "Angular file upload directives", "description": "Angular file upload directives",
"scripts": { "scripts": {
"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 ng2-file-upload-demo --prod", "demo.build": "ng build -prod --aot",
"demo.deploy": "gh-pages -d demo/dist", "demo.deploy": "gh-pages -d demo/dist",
"link": "cd dist/ng2-file-upload/ && npm link && cd ../../ && npm link ng2-file-upload", "link": "ngm link -p src --here",
"lint": "exit 0", "lint": "exit 0",
"disable-lint": "tslint \"**/*.ts\" -c tslint.json --fix --type-check -t prose -e \"node_modules/**\" -e \"dist/**\" -e \"temp/**\" -e \"scripts/docs/**\"", "disable-lint": "tslint \"**/*.ts\" -c tslint.json --fix --type-check -t prose -e \"node_modules/**\" -e \"dist/**\" -e \"temp/**\" -e \"scripts/docs/**\"",
"flow.changelog": "conventional-changelog -i CHANGELOG.md -s -p angular", "flow.changelog": "conventional-changelog -i CHANGELOG.md -s -p angular",
"flow.github-release": "conventional-github-releaser -p angular", "flow.github-release": "conventional-github-releaser -p angular",
"build": "ng build ng2-file-upload", "build": "ngm build -p src --clean",
"build.watch": "ng build ng2-file-upload --watch", "build.watch": "ngm build -p src --watch --skip-bundles",
"start": "ng serve ng2-file-upload-demo --aot", "start": "ng serve --aot",
"pretest": "run-s lint build link", "pretest": "run-s lint build link",
"test": "ng test ng2-file-upload-test", "test": "ng test -sr",
"test-coverage": "ng test ng2-file-upload-test --code-coverage", "test-coverage": "ng test -sr -cc",
"version": "npm run flow.changelog && git add -A" "version": "npm run flow.changelog && git add -A"
}, },
"main": "bundles/ng2-file-upload.umd.js",
"module": "index.js",
"typings": "index.d.ts",
"keywords": [ "keywords": [
"angular2", "angular2",
"bootstrap", "bootstrap",
@@ -40,29 +43,34 @@
"url": "https://github.com/valor-software/ng2-file-upload/issues" "url": "https://github.com/valor-software/ng2-file-upload/issues"
}, },
"homepage": "https://github.com/valor-software/ng2-file-upload#readme", "homepage": "https://github.com/valor-software/ng2-file-upload#readme",
"peerDependencies": {}, "dependencies": {},
"peerDependencies": {
"@angular/common": "^2.3.0",
"@angular/core": "^2.3.0"
},
"devDependencies": { "devDependencies": {
"@angular-devkit/build-angular": "~0.803.0", "@angular/common": "2.4.3",
"@angular-devkit/build-ng-packagr": "^0.803.0", "@angular/compiler": "2.4.3",
"@angular/cli": "^8.3.0", "@angular/compiler-cli": "2.4.3",
"@angular/common": "^8.2.3", "@angular/core": "2.4.3",
"@angular/compiler": "^8.2.3", "@angular/forms": "2.4.3",
"@angular/compiler-cli": "^8.2.3", "@angular/http": "2.4.3",
"@angular/core": "^8.2.3", "@angular/language-service": "2.4.3",
"@angular/forms": "^8.2.3", "@angular/platform-browser": "2.4.3",
"@angular/language-service": "8.2.3", "@angular/platform-browser-dynamic": "2.4.3",
"@angular/platform-browser": "^8.2.3", "@angular/router": "3.4.3",
"@angular/platform-browser-dynamic": "^8.2.3", "@angular/tsc-wrapped": "0.5.1",
"@angular/router": "^8.2.3", "@ngtools/webpack": "1.2.3",
"@types/jasmine": "2.5.40", "@types/jasmine": "2.5.40",
"@types/marked": "0.0.28", "@types/marked": "0.0.28",
"@types/node": "7.0.0", "@types/node": "7.0.0",
"@types/webpack": "^3.8.18", "@types/webpack": "^2.2.1",
"angular-cli": "1.0.0-beta.25.5",
"bootstrap": "3.3.7", "bootstrap": "3.3.7",
"chokidar-cli": "1.2.0", "chokidar-cli": "1.2.0",
"classlist-polyfill": "1.0.3", "classlist-polyfill": "1.0.3",
"codecov": "1.0.1", "codecov": "1.0.1",
"codelyzer": "^5.0.1", "codelyzer": "~2.0.0-beta.4",
"conventional-changelog-cli": "1.2.0", "conventional-changelog-cli": "1.2.0",
"conventional-github-releaser": "1.1.3", "conventional-github-releaser": "1.1.3",
"core-js": "^2.4.1", "core-js": "^2.4.1",
@@ -72,41 +80,40 @@
"gh-pages": "0.12.0", "gh-pages": "0.12.0",
"gitignore-to-glob": "0.3.0", "gitignore-to-glob": "0.3.0",
"google-code-prettify": "1.0.5", "google-code-prettify": "1.0.5",
"html-loader": "^0.5.5", "html-loader": "0.4.4",
"jasmine-core": "3.1.0", "jasmine": "2.5.3",
"jasmine-core": "2.5.2",
"jasmine-data-provider": "2.2.0", "jasmine-data-provider": "2.2.0",
"jasmine-spec-reporter": "4.2.1", "jasmine-spec-reporter": "3.2.0",
"karma": "4.1.0", "karma": "1.4.0",
"karma-chrome-launcher": "2.2.0", "karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1", "karma-cli": "^1.0.1",
"karma-coverage-istanbul-reporter": "1.4.3", "karma-jasmine": "^1.0.2",
"karma-jasmine": "1.1.2", "karma-remap-istanbul": "0.4.0",
"karma-remap-istanbul": "0.6.0", "karma-sauce-launcher": "1.1.0",
"karma-sauce-launcher": "1.2.0",
"lite-server": "2.2.2", "lite-server": "2.2.2",
"lodash": "4.17.4", "lodash": "4.17.4",
"markdown-loader": "^5.1.0", "markdown-loader": "^0.1.7",
"marked": "0.3.6", "marked": "0.3.6",
"ng-packagr": "^5.5.0", "ng2-bootstrap": "1.2.2",
"ngx-bootstrap": "1.6.6", "ng2-page-scroll": "4.0.0-beta.2",
"ngm-cli": "0.4.0",
"npm-run-all": "^4.0.1", "npm-run-all": "^4.0.1",
"pre-commit": "1.2.2", "pre-commit": "1.2.2",
"protractor": "5.0.0", "protractor": "5.0.0",
"raw-loader": "^3.1.0",
"reflect-metadata": "0.1.9", "reflect-metadata": "0.1.9",
"require-dir": "0.3.1", "require-dir": "0.3.1",
"rxjs": "^6.5.2", "rxjs": "5.0.3",
"systemjs-builder": "0.15.34", "systemjs-builder": "0.15.34",
"ts-helpers": "^1.1.1", "ts-helpers": "^1.1.1",
"ts-node": "2.0.0", "ts-node": "2.0.0",
"tsickle": "^0.37.0", "tslint": "4.3.1",
"tslint": "^5.19.0", "tslint-config-valorsoft": "1.2.0",
"tslint-config-valorsoft": "^2.2.1",
"typedoc": "0.5.5", "typedoc": "0.5.5",
"typescript": "3.5.3", "typescript": "2.1.5",
"wallaby-webpack": "0.0.30", "wallaby-webpack": "0.0.30",
"webdriver-manager": "11.1.1", "webdriver-manager": "11.1.1",
"zone.js": "~0.9.1" "zone.js": "0.7.5"
}, },
"contributors": [ "contributors": [
{ {
@@ -129,8 +136,5 @@
"email": "otelnov@gmail.com", "email": "otelnov@gmail.com",
"url": "https://github.com/otelnov" "url": "https://github.com/otelnov"
} }
], ]
"dependencies": {
"tslib": "^1.10.0"
}
} }
+1
View File
@@ -0,0 +1 @@
!**/*.js
+1 -1
View File
@@ -1,4 +1,4 @@
import '../scripts/polyfills.ts'; import '../demo/src/polyfills.ts';
import 'zone.js/dist/long-stack-trace-zone'; import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js'; import 'zone.js/dist/proxy.js';
+1 -1
View File
@@ -8,7 +8,7 @@ declare const ENV:string;
// google code-prettify // google code-prettify
declare const PR:any; declare const PR:any;
// declare const global:any; declare const global:any;
declare module jasmine { declare module jasmine {
interface Matchers { interface Matchers {
+11 -2
View File
@@ -1,6 +1,6 @@
import { Directive, EventEmitter, ElementRef, HostListener, Input, Output } from '@angular/core'; import { Directive, EventEmitter, ElementRef, HostListener, Input, Output } from '@angular/core';
import { FileUploader, FileUploaderOptions } from './file-uploader.class'; import { FileUploader } from './file-uploader.class';
@Directive({selector: '[ng2FileDrop]'}) @Directive({selector: '[ng2FileDrop]'})
export class FileDropDirective { export class FileDropDirective {
@@ -14,7 +14,7 @@ export class FileDropDirective {
this.element = element; this.element = element;
} }
public getOptions(): FileUploaderOptions { public getOptions():any {
return this.uploader.options; return this.uploader.options;
} }
@@ -83,4 +83,13 @@ export class FileDropDirective {
return false; return false;
} }
} }
/*
_addOverClass(item:any):any {
item.addOverClass();
}
_removeOverClass(item:any):any {
item.removeOverClass();
}*/
} }
+8
View File
@@ -1,7 +1,14 @@
import { FileLikeObject } from './file-like-object.class'; import { FileLikeObject } from './file-like-object.class';
import { FileUploader, ParsedResponseHeaders, FileUploaderOptions } from './file-uploader.class'; import { FileUploader, ParsedResponseHeaders, FileUploaderOptions } from './file-uploader.class';
import {Observable} from "rxjs/Rx";
export class FileItem { export class FileItem {
public observer:any;
/**
* Observable for subscribing the server result
*/
public resObservable:Observable;
public file:FileLikeObject; public file:FileLikeObject;
public _file:File; public _file:File;
public alias:string; public alias:string;
@@ -36,6 +43,7 @@ export class FileItem {
this.alias = uploader.options.itemAlias || 'file'; this.alias = uploader.options.itemAlias || 'file';
} }
this.url = uploader.options.url; this.url = uploader.options.url;
this.resObservable=new Observable.create(observer=>{this.observer=observer});
} }
public upload():void { public upload():void {
+1 -2
View File
@@ -7,10 +7,8 @@ export class FileLikeObject {
public size:any; public size:any;
public type:string; public type:string;
public name:string; public name:string;
public rawFile: string;
public constructor(fileOrInput:any) { public constructor(fileOrInput:any) {
this.rawFile = fileOrInput;
let isInput = isElement(fileOrInput); let isInput = isElement(fileOrInput);
let fakePathOrObject = isInput ? fileOrInput.value : fileOrInput; let fakePathOrObject = isInput ? fileOrInput.value : fileOrInput;
let postfix = typeof fakePathOrObject === 'string' ? 'FakePath' : 'Object'; let postfix = typeof fakePathOrObject === 'string' ? 'FakePath' : 'Object';
@@ -26,6 +24,7 @@ export class FileLikeObject {
} }
public _createFromObject(object:{size:number, type:string, name:string}):void { public _createFromObject(object:{size:number, type:string, name:string}):void {
// this.lastModifiedDate = copy(object.lastModifiedDate);
this.size = object.size; this.size = object.size;
this.type = object.type; this.type = object.type;
this.name = object.name; this.name = object.name;
+10 -5
View File
@@ -1,11 +1,12 @@
import { Directive, EventEmitter, ElementRef, Input, HostListener, Output } from '@angular/core'; import { Directive, ElementRef, Input, HostListener } from '@angular/core';
import { FileUploader } from './file-uploader.class'; import { FileUploader } from './file-uploader.class';
// todo: filters
@Directive({selector: '[ng2FileSelect]'}) @Directive({selector: '[ng2FileSelect]'})
export class FileSelectDirective { export class FileSelectDirective {
@Input() public uploader:FileUploader; @Input() public uploader:FileUploader;
@Output() public onFileSelected: EventEmitter<File[]> = new EventEmitter<File[]>();
protected element:ElementRef; protected element:ElementRef;
@@ -18,7 +19,7 @@ export class FileSelectDirective {
} }
public getFilters():any { public getFilters():any {
return {}; return void 0;
} }
public isEmptyAfterSelection():boolean { public isEmptyAfterSelection():boolean {
@@ -27,15 +28,19 @@ export class FileSelectDirective {
@HostListener('change') @HostListener('change')
public onChange():any { public onChange():any {
// let files = this.uploader.isHTML5 ? this.element.nativeElement[0].files : this.element.nativeElement[0];
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 = this.getFilters();
this.uploader.addToQueue(files, options, filters); // if(!this.uploader.isHTML5) this.destroy();
this.onFileSelected.emit(files);
this.uploader.addToQueue(files, options, filters);
if (this.isEmptyAfterSelection()) { if (this.isEmptyAfterSelection()) {
// todo
this.element.nativeElement.value = ''; this.element.nativeElement.value = '';
/*this.element.nativeElement
.replaceWith(this.element = this.element.nativeElement.clone(true)); // IE fix*/
} }
} }
} }
+2 -13
View File
@@ -1,5 +1,3 @@
import { FileLikeObject } from "../index";
export class FileType { export class FileType {
/* MS office */ /* MS office */
public static mime_doc:string[] = [ public static mime_doc:string[] = [
@@ -52,15 +50,10 @@ export class FileType {
'application/compress', 'application/compress',
'application/x-tar', 'application/x-tar',
'application/x-rar-compressed', 'application/x-rar-compressed',
'application/octet-stream', 'application/octet-stream'
'application/x-zip-compressed',
'application/zip-compressed',
'application/x-7z-compressed',
'application/gzip',
'application/x-bzip2'
]; ];
public static getMimeClass(file: FileLikeObject): string { public static getMimeClass(file:any):string {
let mimeClass = 'application'; let mimeClass = 'application';
if (this.mime_psd.indexOf(file.type) !== -1) { if (this.mime_psd.indexOf(file.type) !== -1) {
mimeClass = 'image'; mimeClass = 'image';
@@ -114,18 +107,14 @@ export class FileType {
'mod': 'audio', 'mod': 'audio',
'm4a': 'audio', 'm4a': 'audio',
'compress': 'compress', 'compress': 'compress',
'zip': 'compress',
'rar': 'compress', 'rar': 'compress',
'7z': 'compress', '7z': 'compress',
'lz': 'compress', 'lz': 'compress',
'z01': 'compress', 'z01': 'compress',
'bz2': 'compress',
'gz': 'compress',
'pdf': 'pdf', 'pdf': 'pdf',
'xls': 'xls', 'xls': 'xls',
'xlsx': 'xls', 'xlsx': 'xls',
'ods': 'xls', 'ods': 'xls',
'csv': 'xls',
'mp4': 'video', 'mp4': 'video',
'avi': 'video', 'avi': 'video',
'wmv': 'video', 'wmv': 'video',
+49 -55
View File
@@ -1,4 +1,3 @@
import { EventEmitter } from '@angular/core';
import { FileLikeObject } from './file-like-object.class'; import { FileLikeObject } from './file-like-object.class';
import { FileItem } from './file-item.class'; import { FileItem } from './file-item.class';
import { FileType } from './file-type.class'; import { FileType } from './file-type.class';
@@ -6,7 +5,7 @@ import { FileType } from './file-type.class';
function isFile(value:any):boolean { function isFile(value:any):boolean {
return (File && value instanceof File); return (File && value instanceof File);
} }
// function isFileLikeObject(value:any) {
export interface Headers { export interface Headers {
name:string; name:string;
value:string; value:string;
@@ -14,18 +13,15 @@ export interface Headers {
export type ParsedResponseHeaders = {[headerFieldName:string]:string}; export type ParsedResponseHeaders = {[headerFieldName:string]:string};
export type FilterFunction = { export type FilterFunction = {name:string, fn:(item?:FileLikeObject, options?:FileUploaderOptions)=>boolean};
name: string,
fn: (item?: FileLikeObject, options?: FileUploaderOptions) => boolean
};
export interface FileUploaderOptions { export interface FileUploaderOptions {
allowedMimeType?: string[]; allowedMimeType?:Array<string>;
allowedFileType?: string[]; allowedFileType?:Array<string>;
autoUpload?:boolean; autoUpload?:boolean;
isHTML5?:boolean; isHTML5?:boolean;
filters?: FilterFunction[]; filters?:Array<FilterFunction>;
headers?: Headers[]; headers?:Array<Headers>;
method?:string; method?:string;
authToken?:string; authToken?:string;
maxFileSize?:number; maxFileSize?:number;
@@ -36,45 +32,38 @@ export interface FileUploaderOptions {
itemAlias?: string; itemAlias?: string;
authTokenHeader?: string; authTokenHeader?: string;
additionalParameter?:{[key: string]: any}; additionalParameter?:{[key: string]: any};
parametersBeforeFiles?: boolean;
formatDataFunction?: Function;
formatDataFunctionIsAsync?: boolean;
} }
export class FileUploader { export class FileUploader {
public authToken:string; public authToken:string;
public isUploading:boolean = false; public isUploading:boolean = false;
public queue: FileItem[] = []; public queue:Array<FileItem> = [];
public progress:number = 0; public progress:number = 0;
public _nextIndex:number = 0; public _nextIndex:number = 0;
public autoUpload:any; public autoUpload:any;
public authTokenHeader: string; public authTokenHeader: string;
public response: EventEmitter<any>;
public options:FileUploaderOptions = { public options:FileUploaderOptions = {
autoUpload: false, autoUpload: false,
isHTML5: true, isHTML5: true,
filters: [], filters: [],
removeAfterUpload: false, removeAfterUpload: false,
disableMultipart: false, disableMultipart: false
formatDataFunction: (item: FileItem) => item._file,
formatDataFunctionIsAsync: false
}; };
protected _failFilterIndex:number; protected _failFilterIndex:number;
public constructor(options:FileUploaderOptions) { public constructor(options:FileUploaderOptions) {
this.setOptions(options); this.setOptions(options);
this.response = new EventEmitter<any>();
} }
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 = options.authToken;
this.authTokenHeader = this.options.authTokenHeader || 'Authorization'; this.authTokenHeader = options.authTokenHeader || 'Authorization';
this.autoUpload = this.options.autoUpload; this.autoUpload = options.autoUpload;
this.options.filters.unshift({name: 'queueLimit', fn: this._queueLimitFilter}); this.options.filters.unshift({name: 'queueLimit', fn: this._queueLimitFilter});
if (this.options.maxFileSize) { if (this.options.maxFileSize) {
@@ -92,6 +81,7 @@ export class FileUploader {
for(let i = 0; i < this.queue.length; i++) { for(let i = 0; i < this.queue.length; i++) {
this.queue[i].url = this.options.url; this.queue[i].url = this.options.url;
} }
// this.options.filters.unshift({name: 'folder', fn: this._folderFilter});
} }
public addToQueue(files:File[], options?:FileUploaderOptions, filters?:FilterFunction[]|string):void { public addToQueue(files:File[], options?:FileUploaderOptions, filters?:FilterFunction[]|string):void {
@@ -106,7 +96,6 @@ export class FileUploader {
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 (this._isValidFile(temp, arrayOfFilters, options)) {
let fileItem = new FileItem(this, some, options); let fileItem = new FileItem(this, some, options);
@@ -192,11 +181,11 @@ export class FileUploader {
return typeof value === 'number' ? value : this.queue.indexOf(value); return typeof value === 'number' ? value : this.queue.indexOf(value);
} }
public getNotUploadedItems(): any[] { public getNotUploadedItems():Array<any> {
return this.queue.filter((item:FileItem) => !item.isUploaded); return this.queue.filter((item:FileItem) => !item.isUploaded);
} }
public getReadyItems(): any[] { public getReadyItems():Array<any> {
return this.queue return this.queue
.filter((item:FileItem) => (item.isReady && !item.isUploading)) .filter((item:FileItem) => (item.isReady && !item.isUploading))
.sort((item1:any, item2:any) => item1.index - item2.index); .sort((item1:any, item2:any) => item1.index - item2.index);
@@ -204,6 +193,11 @@ export class FileUploader {
public destroy():void { public destroy():void {
return void 0; return void 0;
/*forEach(this._directives, (key) => {
forEach(this._directives[key], (object) => {
object.destroy();
});
});*/
} }
public onAfterAddingAll(fileItems:any):any { public onAfterAddingAll(fileItems:any):any {
@@ -283,6 +277,7 @@ export class FileUploader {
} }
this.onCompleteAll(); this.onCompleteAll();
this.progress = this._getTotalProgress(); this.progress = this._getTotalProgress();
this.item.observer.next(response);
this._render(); this._render();
} }
@@ -296,11 +291,15 @@ export class FileUploader {
} }
protected _xhrTransport(item:FileItem):any { protected _xhrTransport(item:FileItem):any {
let that = this;
let xhr = item._xhr = new XMLHttpRequest(); let xhr = item._xhr = new XMLHttpRequest();
let sendable:any; let sendable:any;
this._onBeforeUploadItem(item); this._onBeforeUploadItem(item);
// todo
/*item.formData.map(obj => {
obj.map((value, key) => {
form.append(key, value);
});
});*/
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');
} }
@@ -308,28 +307,15 @@ export class FileUploader {
sendable = new FormData(); sendable = new FormData();
this._onBuildItemForm(item, sendable); this._onBuildItemForm(item, sendable);
const appendFile = () => sendable.append(item.alias, item._file, item.file.name); sendable.append(item.alias, item._file, item.file.name);
if (!this.options.parametersBeforeFiles) {
appendFile();
}
// For AWS, Additional Parameters must come BEFORE Files
if (this.options.additionalParameter !== undefined) { if (this.options.additionalParameter !== undefined) {
Object.keys(this.options.additionalParameter).forEach((key:string) => { Object.keys(this.options.additionalParameter).forEach((key:string) => {
let paramVal = this.options.additionalParameter[ key ]; sendable.append(key, this.options.additionalParameter[key]);
// Allow an additional parameter to include the filename
if (typeof paramVal === 'string' && paramVal.indexOf('{{file_name}}') >= 0) {
paramVal = paramVal.replace('{{file_name}}', item.file.name);
}
sendable.append(key, paramVal);
}); });
} }
if (this.options.parametersBeforeFiles) {
appendFile();
}
} else { } else {
sendable = this.options.formatDataFunction(item); sendable = item._file;
} }
xhr.upload.onprogress = (event:any) => { xhr.upload.onprogress = (event:any) => {
@@ -342,7 +328,8 @@ export class FileUploader {
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';
(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._
(item, response, xhr.status, headers);
}; };
xhr.onerror = () => { xhr.onerror = () => {
let headers = this._parseHeaders(xhr.getAllResponseHeaders()); let headers = this._parseHeaders(xhr.getAllResponseHeaders());
@@ -371,18 +358,7 @@ export class FileUploader {
if (this.authToken) { if (this.authToken) {
xhr.setRequestHeader(this.authTokenHeader, this.authToken); xhr.setRequestHeader(this.authTokenHeader, this.authToken);
} }
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
that.response.emit(xhr.responseText)
}
}
if (this.options.formatDataFunctionIsAsync) {
sendable.then(
(result: any) => xhr.send(JSON.stringify(result))
);
} else {
xhr.send(sendable); xhr.send(sendable);
}
this._render(); this._render();
} }
@@ -414,8 +390,13 @@ export class FileUploader {
protected _render():any { protected _render():any {
return void 0; return void 0;
// todo: ?
} }
// protected _folderFilter(item:FileItem):boolean {
// return !!(item.size || item.type);
// }
protected _queueLimitFilter():boolean { protected _queueLimitFilter():boolean {
return this.options.queueLimit === undefined || this.queue.length < this.options.queueLimit; return this.options.queueLimit === undefined || this.queue.length < this.options.queueLimit;
} }
@@ -432,10 +413,17 @@ export class FileUploader {
return (status >= 200 && status < 300) || status === 304; return (status >= 200 && status < 300) || status === 304;
} }
/* tslint:disable */
protected _transformResponse(response:string, headers:ParsedResponseHeaders):string { protected _transformResponse(response:string, headers:ParsedResponseHeaders):string {
// todo: ?
/*var headersGetter = this._headersGetter(headers);
forEach($http.defaults.transformResponse, (transformFn) => {
response = transformFn(response, headersGetter);
});*/
return response; return response;
} }
/* tslint:enable */
protected _parseHeaders(headers:string):ParsedResponseHeaders { protected _parseHeaders(headers:string):ParsedResponseHeaders {
let parsed:any = {}; let parsed:any = {};
let key:any; let key:any;
@@ -455,6 +443,10 @@ export class FileUploader {
return parsed; return parsed;
} }
/*protected _iframeTransport(item:FileItem) {
// todo: implement it later
}*/
protected _onWhenAddingFileFailed(item:FileLikeObject, filter:any, options:any):void { protected _onWhenAddingFileFailed(item:FileLikeObject, filter:any, options:any):void {
this.onWhenAddingFileFailed(item, filter, options); this.onWhenAddingFileFailed(item, filter, options);
} }
@@ -486,11 +478,13 @@ export class FileUploader {
this._render(); this._render();
} }
/* tslint:disable */
protected _onSuccessItem(item:FileItem, response:string, status:number, headers:ParsedResponseHeaders):void { protected _onSuccessItem(item:FileItem, response:string, status:number, headers:ParsedResponseHeaders):void {
item._onSuccess(response, status, headers); item._onSuccess(response, status, headers);
this.onSuccessItem(item, response, status, headers); this.onSuccessItem(item, response, status, headers);
} }
/* tslint:enable */
protected _onCancelItem(item:FileItem, response:string, status:number, headers:ParsedResponseHeaders):void { protected _onCancelItem(item:FileItem, response:string, status:number, headers:ParsedResponseHeaders):void {
item._onCancel(response, status, headers); item._onCancel(response, status, headers);
this.onCancelItem(item, response, status, headers); this.onCancelItem(item, response, status, headers);
+6
View File
@@ -0,0 +1,6 @@
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
-1
View File
@@ -2,6 +2,5 @@ export * from './file-upload/file-select.directive';
export * from './file-upload/file-drop.directive'; export * from './file-upload/file-drop.directive';
export * from './file-upload/file-uploader.class'; export * from './file-upload/file-uploader.class';
export * from './file-upload/file-item.class'; export * from './file-upload/file-item.class';
export * from './file-upload/file-like-object.class';
export { FileUploadModule } from './file-upload/file-upload.module'; export { FileUploadModule } from './file-upload/file-upload.module';
-7
View File
@@ -1,7 +0,0 @@
{
"$schema": "../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../dist/ng2-file-upload",
"lib": {
"entryFile": "index.ts"
}
}
+1
View File
@@ -0,0 +1 @@
export * from './index';
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ng2-file-upload", "name": "ng2-file-upload",
"version": "1.3.0", "version": "1.2.0",
"peerDependencies": { "peerDependencies": {
"@angular/common": "*", "@angular/common": "*",
"@angular/core": "*" "@angular/core": "*"
+7 -126
View File
@@ -1,29 +1,18 @@
import { Component, DebugElement } from '@angular/core'; import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { inject, ComponentFixture, TestBed } from '@angular/core/testing'; import { inject, ComponentFixture, TestBed } from '@angular/core/testing';
import { FileUploader } from '../file-upload/file-uploader.class'; import { FileUploader } from '../file-upload/file-uploader.class';
import { FileUploadModule } from '../file-upload/file-upload.module'; import { FileUploadModule } from '../file-upload/file-upload.module';
import { FileDropDirective } from '../file-upload/file-drop.directive';
@Component({ @Component({
selector: 'container', selector: 'container',
template: `<div type="file" template: `<input type="file" ng2FileSelect [uploader]="uploader" />`
ng2FileDrop
[uploader]="uploader"
></div>`
}) })
export class ContainerComponent { export class ContainerComponent {
public get url(): string { return 'localhost:3000'; } public uploader:FileUploader = new FileUploader({url: 'localhost:3000'});
public uploader: FileUploader = new FileUploader({ url: this.url });
} }
describe('Directive: FileDropDirective', () => { describe('Directive: FileSelectDirective', () => {
let fixture: ComponentFixture<ContainerComponent>;
let hostComponent: ContainerComponent;
let directiveElement: DebugElement;
let fileDropDirective: FileDropDirective;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
@@ -33,115 +22,7 @@ describe('Directive: FileDropDirective', () => {
}); });
}); });
beforeEach(() => { it('should be fine', inject([ContainerComponent], (fixture:ComponentFixture<ContainerComponent>) => {
fixture = TestBed.createComponent(ContainerComponent); expect(fixture).not.toBeNull();
hostComponent = fixture.componentInstance; }));
fixture.detectChanges();
directiveElement = fixture.debugElement.query(By.directive(FileDropDirective));
fileDropDirective = directiveElement.injector.get(FileDropDirective) as FileDropDirective;
}); });
it('can be initialized', () => {
expect(fixture).toBeDefined();
expect(hostComponent).toBeDefined();
expect(fileDropDirective).toBeDefined();
});
it('can set file uploader', () => {
expect(fileDropDirective.uploader).toBe(hostComponent.uploader);
});
it('can get uploader options', () => {
const options = fileDropDirective.getOptions();
// Check url set through binding
expect(options.url).toBe(hostComponent.url);
// Check default options
expect(options.autoUpload).toBeFalsy();
expect(options.isHTML5).toBeTruthy();
expect(options.removeAfterUpload).toBeFalsy();
expect(options.disableMultipart).toBeFalsy();
});
it('can get filters', () => {
const filters = fileDropDirective.getFilters();
// TODO: Update test once implemented
expect(filters).toEqual({});
});
it('handles drop event', () => {
spyOn(fileDropDirective, 'onDrop');
directiveElement.triggerEventHandler('drop', getFakeEventData());
expect(fileDropDirective.onDrop).toHaveBeenCalled();
});
it('adds file to upload', () => {
spyOn(fileDropDirective.uploader, 'addToQueue');
let fileOverData;
fileDropDirective.fileOver.subscribe((data: any) => fileOverData = data);
let fileDropData;
fileDropDirective.onFileDrop.subscribe((data: File[]) => fileDropData = data);
fileDropDirective.onDrop(getFakeEventData());
const uploadedFiles = getFakeEventData().dataTransfer.files;
const expectedArguments = [ uploadedFiles, fileDropDirective.getOptions(), fileDropDirective.getFilters() ];
expect(fileDropDirective.uploader.addToQueue).toHaveBeenCalledWith(...expectedArguments);
expect(fileOverData).toBeFalsy();
expect(fileDropData).toEqual(uploadedFiles);
});
it('handles dragover event', () => {
spyOn(fileDropDirective, 'onDragOver');
directiveElement.triggerEventHandler('dragover', getFakeEventData());
expect(fileDropDirective.onDragOver).toHaveBeenCalled();
});
it('handles file over', () => {
let fileOverData;
fileDropDirective.fileOver.subscribe((data: any) => fileOverData = data);
fileDropDirective.onDragOver(getFakeEventData());
expect(fileOverData).toBeTruthy();
});
it('handles dragleave event', () => {
spyOn(fileDropDirective, 'onDragLeave');
directiveElement.triggerEventHandler('dragleave', getFakeEventData());
expect(fileDropDirective.onDragLeave).toHaveBeenCalled();
});
it('handles file over leave', () => {
let fileOverData;
fileDropDirective.fileOver.subscribe((data: any) => fileOverData = data);
fileDropDirective.onDragLeave(getFakeEventData());
expect(fileOverData).toBeFalsy();
});
});
function getFakeEventData(): any {
return {
dataTransfer: {
files: [ 'foo.bar' ],
types: [ 'Files' ]
},
preventDefault: () => undefined,
stopPropagation: () => undefined
}
}
-99
View File
@@ -1,99 +0,0 @@
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { Component, DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { FileUploadModule } from '../file-upload/file-upload.module';
import { FileSelectDirective } from '../file-upload/file-select.directive';
import { FileUploader } from '../file-upload/file-uploader.class';
@Component({
selector: 'container',
template: `<input type="file"
ng2FileSelect
[uploader]="uploader"
/>`
})
export class ContainerComponent {
public get url(): string { return 'localhost:3000'; }
public uploader: FileUploader = new FileUploader({ url: this.url });
}
describe('Directive: FileSelectDirective', () => {
let fixture: ComponentFixture<ContainerComponent>;
let hostComponent: ContainerComponent;
let directiveElement: DebugElement;
let fileSelectDirective: FileSelectDirective;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ FileUploadModule ],
declarations: [ ContainerComponent ],
providers: [ ContainerComponent ]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(ContainerComponent);
hostComponent = fixture.componentInstance;
fixture.detectChanges();
directiveElement = fixture.debugElement.query(By.directive(FileSelectDirective));
fileSelectDirective = directiveElement.injector.get(FileSelectDirective) as FileSelectDirective;
});
it('can be initialized', () => {
expect(fixture).toBeDefined();
expect(hostComponent).toBeDefined();
expect(fileSelectDirective).toBeDefined();
});
it('can set file uploader', () => {
expect(fileSelectDirective.uploader).toBe(hostComponent.uploader);
});
it('can get uploader options', () => {
const options = fileSelectDirective.getOptions();
// Check url set through binding
expect(options.url).toBe(hostComponent.url);
// Check default options
expect(options.autoUpload).toBeFalsy();
expect(options.isHTML5).toBeTruthy();
expect(options.removeAfterUpload).toBeFalsy();
expect(options.disableMultipart).toBeFalsy();
});
it('can get filters', () => {
const filters = fileSelectDirective.getFilters();
// TODO: Update test once implemented
expect(filters).toEqual({});
});
it('can check if element is empty', () => {
const isElementEmpty = fileSelectDirective.isEmptyAfterSelection();
expect(isElementEmpty).toBeFalsy();
});
it('can listed on change event', () => {
spyOn(fileSelectDirective, 'onChange');
directiveElement.triggerEventHandler('change', {});
expect(fileSelectDirective.onChange).toHaveBeenCalled();
});
it('handles change event', () => {
spyOn(fileSelectDirective.uploader, 'addToQueue');
fileSelectDirective.onChange();
const expectedArguments = [ directiveElement.nativeElement.files,
fileSelectDirective.getOptions(),
fileSelectDirective.getFilters() ];
expect(fileSelectDirective.uploader.addToQueue).toHaveBeenCalledWith(...expectedArguments);
});
});
+19 -15
View File
@@ -1,9 +1,8 @@
{ {
"compilerOptions": { "compilerOptions": {
"baseUrl": ".",
"outDir": "../dist", "outDir": "../dist",
"target": "es5", "target": "es5",
"module": "esnext", "module": "commonjs",
"moduleResolution": "node", "moduleResolution": "node",
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
"experimentalDecorators": true, "experimentalDecorators": true,
@@ -15,19 +14,24 @@
"stripInternal": true, "stripInternal": true,
"noUnusedLocals": false, "noUnusedLocals": false,
"noUnusedParameters": false, "noUnusedParameters": false,
"lib": ["dom", "es6"] "lib": ["dom", "es6"],
}, "types": [
"angularCompilerOptions": { "jasmine",
"annotateForClosureCompiler": true, "webpack"
"strictMetadataEmit": true,
"skipTemplateCodegen": true,
"flatModuleOutFile": "ng2-file-upload.js",
"flatModuleId": "ng2-file-upload"
},
"include": [
"../scripts/typings.d.ts"
], ],
"exclude": [ "typeRoots": [
"**/*.spec.ts" "../node_modules/@types"
] ]
},
"exclude": [
"node_modules"
],
"files": [
"../scripts/typings.d.ts",
"./ng2-file-upload.ts",
"./index.ts"
],
"angularCompilerOptions": {
"genDir": "../temp/factories"
}
} }
-22
View File
@@ -1,22 +0,0 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"target": "es2015",
"outDir": "./out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"../scripts/typings.d.ts",
"test.ts",
"../scripts/polyfills.ts",
],
"include": [
"../src/**/*.spec.ts",
"../demo/src/**/*.spec.ts"
]
}
+7807
View File
File diff suppressed because it is too large Load Diff