I am trying to send my excel file to my asp.net core backend from angular. I can do it in postman easily
But when I try in angular I get error below:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"file": [
"The file field is required."
]
},
"traceId": "00-b1e599ba9962b10481f704228daeddae-372bd43ca76db219-00"
}
My angular http request:
uploadFile(file: File): Observable<any> {
const formData = new FormData();
formData.append('file', file, file.name);
return this.http.post<any>(`${environment.baseApiUri}api/FileLoad/LoadKeepaFile`, formData, {
reportProgress: true,
observe: 'events',
headers: { 'Content-Type': 'multipart/form-data' },
});
}
My component ts
onFileSelected(event: any) {
this.file = event.target.files[0];
if (this.file) {
this.fileName = this.file.name;
}
}
uploadFile() {
if (this.file) {
this.uploadProgress = 0;
this.uploadCancelled = false;
this.productManagementService.uploadFile(this.file).subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
this.uploadProgress = Math.round(100 * (event.loaded / (event.total ?? 1)));
} else if (event.type === HttpEventType.Response) {
this.uploadProgress = null;
// Handle the response from the server here
console.log('File uploaded successfully', event.body);
}
}, error => {
console.error('Upload failed', error);
this.uploadProgress = null;
});
}
}
cancelUpload() {
this.uploadCancelled = true;
this.uploadProgress = null;
this.fileName = null;
this.file = null;
}
My request payload when I send request
I couldn't find solution so I decided to use axios instead. It works well
const formData = new FormData();
formData.append('file', file);
const headers = {
'Content-Type': 'multipart/form-data'
};
// Axios isteğini bir Promise olarak oluştur
const axiosPromise = this.axios.post(`${environment.baseApiUri}api/FileLoad/LoadKeepaFile`, formData, { headers});
// Promise'i Observable'a dönüştür
return from(axiosPromise.then((response: AxiosResponse<any>) => {
if(response?.data?.isSuccess){
this.toastService.success(response?.data?.message);
}else{
this.toastService.error(response?.data?.message);
}
}));