How to append file into formdata angular 2

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> <dbs-input [(ngModel)]="fileName" type="text" placeholder='{{"upload.file_input_placeholder" | translate}}' readonly></dbs-input> <button for="files"> <label for="files">Browse</label> <input type="file" (change)="onChange($event)" [multiple]="multiple" 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(' [], 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.

2

1 Answer

Here it is.

let fileList: FileList = event.target.files; if(fileList.length > 0) { let file: File = fileList[0]; let formData:FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers(); /** No need to include Content-Type in Angular 4 */ headers.append('Content-Type', 'multipart/form-data'); headers.append('Accept', 'application/json'); let options = new RequestOptions({ headers: headers }); this.http.post(`${this.apiEndPoint}`, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) }
use this code inside onChange method3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like