I am starting on angular 11 and am trying to upload a file or multiple files as a post request to my back end API ( that I created in node.js ) Here is the code I used :
web-request.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class WebRequestService {
readonly ROOT_URL;
constructor(private http:HttpClient) {
this.ROOT_URL= 'http://localhost:4000'
}
// observable
get(url:string){
return this.http.get(`${this.ROOT_URL}/${url}`)
}
post(url:string,payload:Object){
return this.http.post(`${this.ROOT_URL}/${url}`,payload)
}
patch(url:string,payload:Object){
return this.http.patch(`${this.ROOT_URL}/${url}`,payload)
}
delete (url:string){
return this.http.delete(`${this.ROOT_URL}/${url}`)
}
}
files.service.ts
import { Injectable } from '@angular/core';
import {WebRequestService} from "./web-request.service";
@Injectable({
providedIn: 'root'
})
export class FilesService {
constructor(private webReqService:WebRequestService) { }
// file to upload should be passed
postFile(fileToUpload: File): Observable<boolean> {
// we want to send a post web request to upload the file
const endpoint = '/upload-txt';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
this.webReqService.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
ReadTable(){
this.webReqService.get('/read-table-csv')
}
}
file-upload.component.html
<div class="file is-primary">
<label class="file-label">
<input
type="file"
id="file"
(change)="handleFileInput($event.target.files)"
/>
<span class="file-cta">
<span class="file-icon">
<i class="fas fa-upload"></i>
</span>
<span class="file-label">Browse Files </span>
</span>
</label>
</div>
file-upload.component.ts
import { Component, OnInit } from '@angular/core';
import {FilesService} from "../../files.service"
@Component({
selector: 'app-files-upload',
templateUrl: './files-upload.component.html',
styleUrls: ['./files-upload.component.scss']
})
export class FilesUploadComponent implements OnInit {
fileToUpload: File | null;
files: File[] = [];
constructor(private fileUploadService: FilesService) {
}
ngOnInit(): void {
}
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}
}
}
How do I fix it, and is there a way I can have the files upload as a drag and drop option as well ?