Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to upload files in angular 2
/**
* Created by Fabian on 19/10/2016.
*/
import { Component, ElementRef, Input } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'file-upload',
template: '<input type="file" [attr.multiple]="multiple ? true : null" (change)="upload()" >'
})
export class FileUploadComponent {
constructor(private http: Http,
private el: ElementRef
) {}
@Input() multiple: boolean = false;
upload() {
let inputEl = this.el.nativeElement.firstElementChild;
if (inputEl.files.length == 0) return;
let files :FileList = inputEl.files;
const formData = new FormData();
for(var i = 0; i < files.length; i++){
formData.append(files[i].name, files[i]);
}
this.http
.post('/api/test/fileupload', formData)
.subscribe();
}
}
@rluckez

This comment has been minimized.

Copy link

commented Nov 16, 2016

It worked like a charm!
Thanks!!!

@OdaiTu

This comment has been minimized.

Copy link

commented Feb 3, 2017

thank you its nice ,but if i have a form with other data like name age city .. etc
how can i upload the hole form with photo in json to the server ?

i already send the json to the server but i cant append the photo with it !
so if u can help me plz

@mulhaq1

This comment has been minimized.

Copy link

commented Jun 8, 2017

I am facing this error

ERROR TypeError: Cannot read property 'length' of undefined

let files :FileList = inputEl.files; // it returns undefined

@justmatt25

This comment has been minimized.

Copy link

commented Dec 20, 2017

@mulhaq1 did you solve this issue? I have the same error

@justmatt25

This comment has been minimized.

Copy link

commented Dec 20, 2017

Just in case anyone else ever comes across the error mentioned by @mulhaq1 it is caused by having the input nested inside of other divs. To solve, put the input inside of its own component and wrap the input in any divs in the template and it should work.

@mdmota

This comment has been minimized.

Copy link

commented May 23, 2018

I have the same problem on primeng + ie9

fileupload.js line 89. files is undefined after choose one file
error

@c17r

This comment has been minimized.

Copy link

commented Jun 13, 2018

@mdmota IE9 doesn't support the File Api: https://caniuse.com/#feat=fileapi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.