I am quite new to Angular 2, please consider it.
I am facing a problem with uploading a file to the node server using angular 2. It works fine using postman:
Postman snapshot:
However, when I use the Angular2 application to send a file to the server, it does nothing:
Angular HTML Component
<label for="file1">Upload PDF version: </label>
<form class="form-inline">
<div class="form-group">
<input type="file" id="file1" #abc name="fileToUpload" class="form-control" placeholder="Upload PDF">
</div>
<button class="btn btn-primary" type="submit" (click)="onUpload(abc)">Upload</button>
</form>
Angular TS component:
import { Component, OnInit } from '@angular/core';
import { UploadService } from './upload.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {
// file1 = document.getElementById("file1");
constructor(private uploadService: UploadService) { }
ngOnInit() {
}
onUpload = (file: File) => {
this.uploadService.uploadfile(file)
.subscribe((res) => {
console.log(res);
},
(err) => {
console.log(err);
});
}
}
Service component:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UploadService {
constructor(private http: HttpClient) {
}
uploadfile(file: File): Observable<File> {
console.log(file);
return this.http.post<File>("http://localhost:3000/fileupload", file, { headers: { 'Content-Type': 'application/json' } });
}
}
Of course, I must be missing something here. I request you all, to please provide some solution.