Upload File with Angular 4 does not work. Result undefind

Issue

Upload File with Angular 4 does not work. Result undefined.

The file information comes along with the event, however the FormData does not work and makes the result undefined.

Html File

<form #form="ngForm" enctype="multipart/form-data" novalidate>
    <input type="file" id="sef" name="sef" class="form-control" ngModel  (change)="getSef($event)">      
    <button class="btn btn-primary" (click)="envirArquivos(form.value)">Enviar</button>
</form>

TS file

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'mw-compare-nfe',
    templateUrl: './compare-nfe.component.html'
})
export class CompareNFEComponent implements OnInit {

    arquivoZip: any

    getZip(event) {
        let fileList: FileList = event.target.files;
        let file: File = fileList[0];

        console.log(file) . <--- The object file is defined.

        let formData: FormData = new FormData();
        this.arquivoZip = formData.append('File', file, file.name);

    }

    constructor() { }

    ngOnInit() {
    }

    envirArquivos(order: Order) {
      console.log(this.arquivoZip) . <--- Undefined
    }

}

Solution

FormData.append will add/append current value to the formData intance you have created, but itself doesn’t return the instance, see DOCS.

So you have to append the file and set it to your component’s filed at separate lines

let formData: FormData = new FormData();
formData.append('File', file, file.name);
this.arquivoZip = formData;

Answered By – Pengyy

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.