Skip to content

Instantly share code, notes, and snippets.

@loiane
Forked from arciisine/Simple File Upload Component
Created December 11, 2016 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loiane/2e8faa220b08024421800df5c5eaea24 to your computer and use it in GitHub Desktop.
Save loiane/2e8faa220b08024421800df5c5eaea24 to your computer and use it in GitHub Desktop.
import { Component, Input, AfterViewInit } from '@angular/core';
import { NgModel, DefaultValueAccessor, NgControl } from '@angular/forms';
import { Http, Headers, RequestOptions } from '@angular/http';
@Component({
selector: 'app-file-uploader',
template: '<input type="file" (change)="updated($event);">',
providers: [NgModel, DefaultValueAccessor]
})
export class FileUploaderComponent implements AfterViewInit {
static ROOT = '/rest/asset';
@Input() private companyId: string = '';
private value: string;
private changeListener: Function;
constructor(private http: Http, private input: NgControl) {
this.input.valueAccessor = this;
}
ngAfterViewInit() {
}
writeValue(obj: any): void {
this.value = obj;
}
registerOnChange(fn: any): void {
this.changeListener = fn;
}
registerOnTouched(fn: any): void {
}
updated($event) {
const files = $event.target.files || $event.srcElement.files;
const file = files[0];
const formData = new FormData();
formData.append('file', file);
const headers = new Headers({});
let options = new RequestOptions({ headers });
let url = FileUploaderComponent.ROOT + (this.companyId ? '/' + this.companyId : '');
this.http.post(url, formData, options).subscribe(res => {
let body = res.json();
this.value = body.filename;
if (this.changeListener) {
this.changeListener(this.value);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment