1

How can I send a file image in angular2 to my backend? I have this in my component.html:

<input type="file" [(ngModel)]="selectedImage" />
<button  (click)="uploadImage($event, selectedImage)">Save</button>

but in my function, selectedImage is undefined.

uploadImage($event, file) {
    console.log(file); //file is undefined
}
Matthew Woo
  • 1,288
  • 15
  • 28
LorenzoBerti
  • 6,704
  • 8
  • 47
  • 89

2 Answers2

1

You can use

<div>
    <input type="file" (change)="onChange($event)"/>
</div>

and in the JavaScript:

onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
}

Do not forget to

import {Component, EventEmitter} from '@angular/core';
Matthew Woo
  • 1,288
  • 15
  • 28
mohamed
  • 31
  • 5
0

You can use ng2-file-upload!

npm install ng2-file-upload --save

Link here: http://valor-software.com/ng2-file-upload/

love prince
  • 149
  • 1
  • 7