I am uploading a excel file from angular 7 to web API using below code:
<input type="file" (change)="fileEvent($event);">
public fileEvent($event) {
const fileSelected: File = $event.target.files[0];
this.masterService.UploadExcel(fileSelected)
.subscribe((response) => {
console.log('set any success actions...');
return response;
},
(error) => {
console.log('set any error actions...');
});
}
fileToUpload: File = null;
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
Service code:
UploadExcel(url: string, data: any): Observable<any> {
this.spinner.show();
// headers.append('Content-Type', 'multipart/form-data');
let headers = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + sessionStorage.getItem('auth_token'),
'CompanyId': sessionStorage.getItem('companyId')
});
debugger;
return this.http.post<any>(AppSettings.apiEndPoint + 'ExcelExample/UploadExcel', data, { headers: headers }).pipe(
map((res: any) => {
this.spinner.hide();
return res
}),
catchError((errorRespnse: any) => {
this.spinner.hide();
var tempMessage = undefined;
tempMessage = errorRespnse.error.ModelState.error[0];
if (tempMessage != undefined) {
this.notificationService.smallBox('error', tempMessage);
}
else {
this.notificationService.smallBox('error', 'Something went wrong, please contact your administrator.');
}
return Observable.throw(errorRespnse);
}));
}
and also try with below service code:
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = AppSettings.apiEndPoint + 'ExcelExample/UploadExcel';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
let headers = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + sessionStorage.getItem('auth_token'),
'CompanyId': sessionStorage.getItem('companyId')
});
return this.http
.post(endpoint, formData, { headers: headers })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
API controller code :
[Route("UploadExcel")]
[HttpPost]
public string ExcelUpload()
{
string message = "";
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
// getting 0 count
if (httpRequest.Files.Count > 0)
{
}
}
From API side I am getting 0 files count.
I also try with below URLS: