Skip to content

Instantly share code, notes, and snippets.

@arciisine
Created October 16, 2016 15:22
Show Gist options
  • Save arciisine/ee57727e56cbc5e83739b2c24fd69658 to your computer and use it in GitHub Desktop.
Save arciisine/ee57727e56cbc5e83739b2c24fd69658 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);
}
});
}
}
@OdaiTu
Copy link

OdaiTu commented Feb 4, 2017

its a great rellay
so i can post a image and other data like name , city and age with the same request ?
and what if i set the input tag to multible ?
i can upload more thann one image ?

@jzapantis
Copy link

When I use this code I get no provider for ngModel

@b0rgbart3
Copy link

This example doesn't work for me.

If I output the file object, I get a full File Object with all the details listed in the console.
But if I output the formData Object (immediately after the append command) - the formData object is completely empty.
?? Any ideas why the append isn't working?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment