import {Component } from 'angular2/core';
import {UploadService} from './app.service';
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" (change)="onChange($event)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
constructor(private service:UploadService) {
this.service.progress$.subscribe(
data => {
console.log('progress = '+data);
});
}
onChange(event) {
console.log('onChange');
var files = event.srcElement.files;
console.log(files);
this.service.makeFileRequest('http://localhost:8182/upload', [], files).subscribe(() => {
console.log('sent');
});
}
}
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
bootstrap(AppComponent);
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 QuickStart</title>
<!-- 1. Load libraries -->
<!-- IE required polyfills, in this exact order -->
<script src="https://code.angularjs.org/2.0.0-beta.3/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.3/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.3/angular2.dev.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.3/http.dev.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {
'app': {
defaultExtension: 'ts'
}
}
});
System.import('app/main')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Rx';
@Injectable()
export class UploadService {
constructor () {
this.progress$ = Observable.create(observer => {
this.progressObserver = observer
}).share();
}
private makeFileRequest (url: string, params: string[], files: File[]): Observable {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
}