Having some trouble trying to upload a file using angular 4, even after closely following a tutorial. I'm not sure where I might be going wrong, so any help in spotting the issue would be greatly appreciated. Here is the code snippet:
import { Component, OnInit } from '@angular/core';
import { ConnectionManagerComponent } from 'src/app/connection-manager/connection-manager.component';
import { ViewChild } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { Validators } from '@angular/forms';
@Component({
selector: 'app-new-contact-list.component',
templateUrl: './new-contact-list.component.html',
styleUrls: ['./new-contact-list.component.css']
})
export class NewContactListComponent implements OnInit {
@ViewChild(ConnectionManagerComponent) connectionManager:ConnectionManagerComponent;
form:FormGroup;
selectedFile: File;
onFileChanged(event) {
this.selectedFile = event.target.files[0]
}
constructor(private fb: FormBuilder,public router:Router) {
this.form = this.fb.group({
name: ['', Validators.required],
fileName: ['', Validators.required],
});
}
ngOnInit() {
}
addContactList()
{
const val = this.form.value;
let contactListName = val.name;
const fd = new FormData();
fd.append("name" ,contactListName);
fd.append('file', this.selectedFile,this.selectedFile.name);
console.log(fd);
this.connectionManager.post('/contactGroups', res => {
console.log(res);
this.router.navigateByUrl('/newContactList');
},fd);
}
}
<div class="input-group">
<input style="display: none" id="fileName"
formControlName="fileName"
type="file"
(change)="onFileChanged($event)"
#fileInput>
<button (click)="fileInput.click()">Select File</button>
</div>