How to append file into formdata angular 2

Viewed 13347

i am doing a file upload component. I need to submit a formdata object for that. I cant append a file or anything to formdata object for some reason. The following is my code;

import {Component, ElementRef,
        ViewChild,EventEmitter, Input, Output, OnInit, OnDestroy} from "@angular/core";
import { UploadService } from './file-upload.service';

@Component({
    selector: 'dbs-file-upload',
    template: `  <div class="file-upload-wrapper">
                    <dbs-input [(ngModel)]="fileName" type="text" class="input-long" placeholder='{{"upload.file_input_placeholder" | translate}}' readonly></dbs-input>
                    <button class="btn-browse" for="files">
                        <label for="files">Browse</label>
                        <input type="file" (change)="onChange($event)"
                                [multiple]="multiple"
                                id="files" style="visibility:hidden;"
                                accept=".csv, text/xml, application/xml, application/vnd.ms-excel"
                                #fileInput>
                        <img src="/images/ico_browse_plus.png">
                    </button>
                </div>`,
    styleUrls: ['./file-upload.component.scss'],
    providers: [UploadService]
})


export class FileUploadComponent implements OnInit{

    @Input() fileName: string;
    @Output() onSelect = new EventEmitter<any>();
    @Input() multiple: boolean = false;
    // @ViewChild('fileInput') inputEl: ElementRef;

    constructor(private service: UploadService) {
        // this.service.progress.subscribe(data => {
        //     // console.log(data);
        // })
    }

    ngOnInit() {

    }

    onChange(event) {
            var files = event.srcElement.files;
            console.log('filesss', files);
            if (files.length > 0) {
                let fd: FormData = new FormData();
                let xhr: XMLHttpRequest = new XMLHttpRequest();
                console.log(xhr, 'FAFAAJHAKB');
                for (let file of files) {
                    fd.append('files', file, file.name);
                }
                console.log(fd, 'FROM COMPAKAP');
            }
            this.fileName = files[0].name;
            this.onSelect.emit(files[0]);

            // this.service.makeFileRequest('http://localhost:8080/mock/upload-file-list.json', [], files).subscribe(() => {
            //     console.log('whyy why');
            // })
        }
}

Am trying to append a file object, when i console.log, the formdata object contains nothing. by right it should get the appended file atleast. can someone tell me what going wrong here? Thanks in advance. First time in my life i am doing a file upload code.

1 Answers
Related